Question

between this

<script src="js/script.js"></script>

and that

<?php
    echo '<script>';
    include 'js/script.js';
    echo '</script>';
?>

Which is better?
I'm actually wondering about things like HTTP Request and others stuffs...

(the same goes for CSS styles, should I put everything in the same file and send to the user, thus reducing the amount of requests, or should I properly separate just like everyone else do? thus increasing the number of requests)

There is something else that I should be concerned about?

Was it helpful?

Solution

Ok, it took me second to figure out what you were asking. In your first choice you are outputing a script tag that links to your javascript, in the second you using PHP to include your javascript inline.

Of the two choices, the first is by far the best. Assuming your page content is dynamic, due to browser caching, for every page a person downloads from you, the same javascript will be included everytime. If your javascript is 100kb in size, every page is now an extra 100kb. Over time this will add up for both your server and your clients.

Including your Javascript (and CSS) by linkages allows the browser to cache pages, and only fetch what is necessary. This will similarly reduce the number of requests as a browser will only fetch what is necessary, which in most cases is just the HTML page.

edit: What if the script is used on only one page?

Still include the Javascript by a link, rather than inline. If you page is 100% static, but has thats not one page but many. And each request will get a new output, with the same replicated Javascript. Even if your page is pure-static HTML, still include it by a link as you never know when you might want to reuse the Javascript (or CSS) code.

OTHER TIPS

I would consider something like this

<script src="js/js.php"></script>

where js.php includes all the need js files I assume this will resolve the caching issue, plus you can make things dynamic by adding get values I guess.

btw I find it better to use the php open and close tags for html whenever possible

   <script src="<?php echo $var ?>" ></script>

As I commented before, <script src="js/script.js"></script>.

This is in you <head> and it will be implemented before anything goes into you <body>

Since you are building your front end via JavaScript, php functionality will come after everything was built by JS.

Well according to me using the later approach is better , if you are designing a php page it is always better to write everything in php , whereas HTML side scripting is better done inside echo"" or print""; functions , you can read a lot about it in w3schools.com , hope my answer solved your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top