phpresourcesincludesaveserver-load

Would it be better to include() resources (css,js) or to let the browser do another request?


Would it be faster include a javascript file and outputting it in the html as a <script> or just use the src attribute and let the browser make another request?

Simply outputting it instead of letting the browser make another request would obviously mean less requests and possibly less server load, but does it make it faster? Including the files and outputting them doesn't let the browser cache them.


Solution

  • If you include it, every different page will have the overhead of downloading the script again.

    If you externally link to it, and send future expiry headers and use versioning with a cache buster (for changes), your file will be downloaded once as per required. On the topic of performance, be sure to minify or pack your production use JavaScript.

    Of course, this is very relevant to your JavaScript. If it is a few lines and likely not to change, maybe you could save that one HTTP request and place it inline.

    99% of the time, however, in an external file is best practice.