There are coutless examples of dynamically loading libraries, but almost all of them follow a very rigid pattern. It’s very difficult or awkard to specify where you want the files loaded.
E.G. Maybe you need the library loaded into the <body> insted of the <head>.
I needed something really simple where I could specify where all the libraries are stored and then tell the loader where they must go via querystring (actually just the “?” part). In principle, this follows the same ideas I put together last year on building dashboards.
WARNING: The WordPress source code formatter really screws up things here and there (adding extra spaces, removing quotes, changing > to > etc…) Check for errors before using this code.
For this example, here is the convention (this all goes in the <head> tag) :
First the location of all the script libraries
<script type="text/javascript"> var scriptDir = "../lib/shared/js/"; </script>
Then call the loader with all the libraries…
<script type=”text/javascript” src=”setup.js?head[lib1,lib2,lib3]body[lib4,lib5]“></script>
What does this do? Basically lib1.js, lib2.js and lib3.js are called into the head (note the “.js” extension and folder location is absent).
This is the same as calling …
<script type=”text/javascript” src=”../lib/shared/js/lib1.js”></script>
<script type=”text/javascript” src=”../lib/shared/js/lib2.js”></script>
<script type=”text/javascript” src=”../lib/shared/js/lib3.js”></script>
… in the <head> tag and …
<script type=”text/javascript” src=”../lib/shared/js/lib4.js”></script>
<script type=”text/javascript” src=”../lib/shared/js/lib5.js”></script>
… in the <body> tag.
And here’s the script for “setup.js” :
// Get the head and body tags
// Find the first instance (index = 0) of the head tag
var he = document.getElementsByTagName(“head”)[0];
// Find the first instance of the body tag
var bo = document.getElementsByTagName(“body”)[0];
// Find all script tags
var j = document.getElementsByTagName(“script”);
// Find this file “setup.js”
for (var i=0;i
{
// Get everything inside the “head[…]”
// portion separated by comma and put into an array.
var fh = f.match(/head\[(.*?)\]/)[1].split(‘,’);
// For each instance of a library, call the loader
for(var i=0; i < fh.length; i++)
loadJS(l + fh[i] + ".js", true);
}
// If there are scripts going in the body tag...
if(f.indexOf("body[") > -1)
{
// Get everything inside the “body[…]” portion
// functionality is the same as above
var fb = f.match(/body\[(.*?)\]/)[1].split(‘,’);
// For each instance of a library, call the loader
for(var i=0; i < fb.length; i++)
loadJS(l + fb[i] + ".js", false);
}
}
catch(err)
{
// Do nothing
}
}
// Script loader
function loadJS(p, h)
{
// Create a tag
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = p;
// If "true" I.E. it goes in the ...
if(h)
he.appendChild(s);
else
bo.appendChild(s);
}[/sourcecode]