Your web server will take care of caching for you if you're just serving up regular .js
files. The .js
files will be downloaded the first time they are linked from one of your pages. When the user re-loads that page, or goes to another page entirely that uses the same .js
file, the browser will used the cached copy. This applies when you load scripts via <script src="code.js"></script>
tags.
That's if you have standalone, separate .js
files. If, on the other hand, you JavaScript code buried in the HTML your PHP scripts generate, for example:
<script type="text/javascript">
alert("Hello world!");
</script>
...these scripts will be re-generated each time your .php
file is loaded. If you're looking to cache the output of your PHP scripts then you will need to manage caching yourself by setting the appropriate HTTP headers from your PHP scripts, be that via the Cache-Control
family of headers or the If-Modified-Since
and ETag
style of headers.
Caching and PHP files don't generally go together, though, since you're usually generating dynamic content that changes based on user input, the time of day, cookies, etc. As caching is purely an optimization the general programming warning against premature optimization applies. If you mess up your HTTP headers you can cause yourself a lot of headaches (believe me on that!). As a rule of thumb, you can probably just let Apache or IIS take care of advanced HTTP things like this and only muck around with HTTP headers if you have a specific need to do so.