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
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.
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.