Search code examples
phpincludehttp-request

PHP - include instead of <script>


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?


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.