0

I would like to do a dynamic include of my .css and .js file within the head tags in my header.php that depend on the current .php file that is open. So it will save some loading time if the .js or .css file is not needed for the current .php page.

So I thought I check the current url if it includes (strpos) a spicific string (e.g. "mycollection.php") and if yes echo the <link> and <script> tags to include the .css or .js files for the current, opened php file. But it seems to be hard to do a clean script this way. Does anyone has a clean, short and better solution for this problem?

Thank you in advance!

3
  • 1
    What you have described looks like a good try, what was hard about it ? If you showed your try in code that will make it easier. Commented Dec 16, 2018 at 12:13
  • 2
    Don't forget that even if you need a .css or .js only for certain pages, once it's loaded in the client (browser), it will be cached and not loaded again until the browser cache is cleared. Maybe it's not such a big deal to just include those files in all your head tags. Commented Dec 16, 2018 at 12:23
  • okay So maybe I think I will give it a try to load it on every page due to mumpitz answer! Thank you very much! If anyone has a code snippet that would be awesome as well of course! Commented Dec 16, 2018 at 12:42

2 Answers 2

1

Try code below :

<!DOCTYPE html>
<html>
<head>
<?php
$get_url=$_SERVER['REQUEST_URI'];
$get_extension=explode('/',$get_url);
$get_extension_php=end($get_extension);
if($get_extension_php=='mycollection.php')
{
    echo '<link href="your.css"/>';
    echo '<script src="your.js"></script>';
}
?>
</head>
<body>
</body>
</html>

Hope it helps you

Sign up to request clarification or add additional context in comments.

Comments

0

I used it before but not in the link but before the include of the header and it was like that

if (!isset($css){ echo "<link></link>;}

and at the header of the page if I didn't need to include the css file I just declare the variable $css = ''; and here we go hope this what you were asking for

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.