Ask HN: Include JavaScript via PHP or HTML?
So in my regular website building duties I have noticed that including the text of my javascript file renders the page faster than if the javascript file was merely include via html.
(In PHP)
<script type="text/javascript" src="stuff.js"></script>
v.s.
<script type="text/javascript"><?php require_once("stuff.js");?></script>
Is there any downside to me including the file via php?
7 comments
[ 2.3 ms ] story [ 22.7 ms ] threadI understand why loading the page would be faster if it was all in one file. Also, I realise that this would not allow for the dynamic page to be cached properly for future use, but I have tested and the effects of the lack of caching are minimal.
So the question is what are the downsides of doing it this way?
The downside is it makes each page bigger. If isn't a real small javascript file, you are adding all those bytes to each request. In this case, it would require more bandwidth to transfer the entire page at the same speed.
It will determine if the file has been included at anytime during that process and only include it if it wasn't previously there. This is a little slower than a direct include() because of the table look up first.
This could be causing it to render slow if you use 'require_once' a lot for the processing of your page. In your example, the lookups could cause your page to load slower. Note that if you type in your javascript via HTML no other processing is done as its treated as part of a text block.
Now with some context, to speed up the load of the page you should use include() instead of require_once. You must insure that this has only happened once per file during the processing of the request, or it will include that code again. This could cause a class redefinition error or bootstrap code to be run more than once.
If keeping track of that stuff gets tricky - its a sign that your PHP program is not structured enough to determine request-flow. Look into interfacing through a dispatcher and brush up on MVC best-practices.
I hope I was of help :)
Edit: After re-reading the question I realized I was answering the wrong question but this is probably a good tidbit about PHP so I'll elect to leave it. The other responders are right on in this case.