I was wondering if there is a javascript "include" function (similar to the one in python), and I was looking for something but couldn't find anything except $.load()
and google.load()
.
So, I ventured out to create a script which could do that just for fun, so:
var include = function( lib ) {
// start with jQuery
if(lib == "jquery") {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery.min.js";
script.defer = "defer"; // should I use script.setAttribute('defer', 'defer')?
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(script, s);
}
}
And then, in a separate script:
include("jquery");
$("p").innerHTML = "Worked!";
But I got an error $ is not defined
Which makes sense, because the script is running before jQuery is loaded. So my question is, is there a way to make sure the include script runs before anything else ahead of it? I've seen callback
solutions that look something like this:
include("http://code.jquery.com/jquery.min.js", function() {
$("p").innerHTML = "Worked!";
});
But I do wonder if there is anything (like I proposed above) that's a little more neat.
Any help would be much appreciated!