Can anyone please recommend the best and easiest way to include multiple Javascript files on a (PHP based) web page?
I have a website that uses jQuery, and anything up to around 10 plugins on any one particular page. I'm not entirely sure of the best way to go about including all these files to make life simple for me as a dev, and to ensure that they are best served to a user.
Ideally I thought the easiest way myself would be to build a PHP handler file that I could use to call which plugins I reqire for each page, and then have it output javascript that used document.write() to 'include' each plugin JS file on the page, like so:
<script src="handler.php?jquery,plugin1,plugin2,plugin3,plugin4"></script>
which might then output Javascript with multiple document.write()'s to each individual plugin.
I am led to believe this might lead to problems with browser caching however, as some browsers ignore caching of items with query strings.
Is this OK to do, or is there a simpler method that I'm perhaps missing?
5 Answers 5
you could be interested in Google AJAX API, i.e.:
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.1");
google.load("prototype", "1.6.0.3");
1 Comment
Joely,
Browsers have no problem caching url's with questionmarks. It's probably better to not include a js file, which in turn includes another js file. If you are already writing a script that manages all the js files that are supposed to be included, why not output all those script tags right there?
1 Comment
Why not just include each of the files individually with their own <script> tag? Then everything gets cached individually and all is well. It'll only be a lot of HTTP requests on the first page load. Dynamically building an "include file" every time will probably not be any better for performance.
Does the combination of scripts vary heavily? If you really want to reduce HTTP requests and you're always including the same 10 files, just put them all together into one long file.
2 Comments
If you're really averse to including the files individually, you could probably write a php function to generate the script tags given a list of plugin names.
function loadScripts(funcs){
//funcs being an array list of paths to the scripts.
var temp;
//lets get a reference to the head tag
var h = document.getElementsByTagName('head')[0];
for(var i=0; i < funcs.length; i++){
temp = document.createElement('script');
temp.setAttribute('src', funcs[i]);
temp.setAttribute('type', 'text/javascript');
h.appendChild(temp);
}
}