I have some javascript code in the most of my php files(different javascript code in each file but maybe some functions are also used in more than one files) Is it a good idea to put all the javascript code from all of my pages into one file and just include this file in each page(using the include php function)? Thank you in advance!
2 Answers
If the JavaScript code isn't generated dynamically, it'd be better to put it into a separate .js file. That way, the browser can download it once, and then use the same cached copy across multple PHP pages.
If you copy the JavaScript code into each PHP file, the browser will have to download those duplicate copies. And the output of a PHP page is often not cacheable, which means that the browser would end up re-downloading that JavaScript code each time you reload the same page.
Comments
Yes, you want to separate your JavaScript from your PHP. However, you don't want to use the PHP include() function to make use of your scripts. In the head of your DOM, just use a script tag with a src attribute.
<head>
<script type="text/javascript" src='path/to/file.js'></script>
</head>