dynamically loading javascript
As near as I can tell, Javascript lacks a function to load more Javascript from a URL. There’s eval(), but that takes strings so it’s a bit of work. The usual hack is to add a <script> tag dynamically to the document which as a side effect causes the page to load the referenced script. Here’s a wrapper function for that, courtesy of this July 2009 writeup:
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
It’s overkill, but it’s cut and paste.I needed this to add jQuery to a page so I could then dump the URLs out of it with $("a").each(console.log(this.href))
Mike tells me he uses this bookmarklet to add D3 to pages. Node.js has the require() function. If you’re serious about dynamic code loading in browsers then requirejs looks good.