Reputation: 2627
I need your opinions and knowledge on a subject.
I'm developing on a website that uses a good amount of JavaScript. In a script tag at the end of the body tag I call a PHP file, which gathers all my JS files and combines/compresses them into one (shorter) file, so I can reduce the number of HTTP calls to the server.
This is all fine and somewhat standard. Now here is my question: Wouldn't it be faster and easier to exclude the src attributed script tag and just output all the JavaScript directly into the script tag in the first place? Wouldn't that save the call from the received PHP file on the users browser back to the server again to collect those JS files?
To clear it up a little: Instead of the user first having to download an HTML file, which then calls back to the server to get the JS file (output from the PHP file), he/she would just download one html file which then had the JS "hardcoded" into a script tag and thereby cutting the second server call.
Is this a reasonable idea? Is it a bad idea to include the javascript directly into the page? It's all dynamically created... It's normally best practice to include JS files, but it seems that that would only load the server even more... Am I onto something or should I just let it be?
Looking forward to hear what you have to say,
Regards Mikkel, Denmark
Upvotes: 1
Views: 125
Reputation: 62884
If you're generating reams of dynamic javascript, just sticking it inside a script tag is a fine idea.
However, if there is any boilerplate javascript that will get loaded on every request, you'd want to factor that out into an optimized external file for the sake of caching.
But anything that is dynamically-generated per-request should go inside a script tag in your main page body, to avoid that extra http request.
Upvotes: 1
Reputation: 40673
If you're creating custom JS for each and every page on your site, then, yes, you'd want to inject that right on to the page instead of having the browser do a roundtrip request for the .js file after page renders.
If, on the other hand, you are reusing large amount of javascript from page to page on the site, you'd want to be referencing it as an external file so the browser caches it.
Upvotes: 2
Reputation: 157839
Just add a conditional GET into your js gathering script and you will be fine.
Upvotes: 1