Reputation: 189
I am new to Javascript and development in general and have an absolute beginner's question: I would like to know more about the advantages and disadvantages of the following two constellations, especially regarding execution speed and server load/requests.
Put all custom JS code inside PHP code and call it from there
Put all custom JS code inside a custom.js and just call the JS functions in PHP
On the one hand I prefer to keep all my JS code separated to have things tidy and clean but on the other hand I imagine that it takes longer to load the page due to an additional server request. Will there be a noticeable speed difference when I put all code in a custom JS file? Are there any specific scenarios where it's recommend to put the JS inside the PHP or keep it separated?
Thanks
Upvotes: 1
Views: 128
Reputation: 6304
Http requests run in parallel, so loading a js file may not be noticeable at all, assuming you have to wait for images and other assets to load as well. The benefits outweigh the potential drawback.
As an added bonus, js files are normally cached, while html is reloaded each time a page is requested.
NOTE: If you have a significant number of scripts, you will have problems with load speed since browsers have limits of how many requests can be made in parallel. In this case you should be looking into minifying and combining them. Try code.google.com/p/minify for automatic minification using php.
Last: Having js code in php is terrible for maintainability.
Upvotes: 2
Reputation: 12815
JS in separate file - additional request. But I would not say that is a problem because it will be cached by browser. If you have a lot of js files - collect them into a single file to avoid multiple requests (there are special tools to compile separate JS files into one file and minimize its size).
Placing it into PHP code is just terrible. It should be in separate file.
On the one hand I prefer to keep all my JS code separated to have things tidy and clean but on the other hand I imagine that it takes longer to parse the whole code.
Why? JS is executed on client side. Not on server side. PHP will not parse JS files. At the same time - if you will put a JS code in PHP file - PHP will need to echo it to browser and that is additional work for PHP engine. Plus, in PHP code it will be sent to browser any time when PHP is executed.
Upvotes: 1
Reputation: 3959
Always err on the side of clean readable code, lest you fall into the premature optimization trap.
You can always refactor underperforming code to make it faster, it's much harder to move from low-level optimizations to a more abstract design, than the other way around (abstract to low-level)
Upvotes: 0