Recently I had need to load jQuery dynamically. I wanted to load jQuery and then as soon as the script tag was in place and jquery was ready I wanted to be able to use it. So #1 I needed jQuery to load dynamically and #2 I needed to be able to add a handler to the script tag to make things happen immediately upon doing so in all browsers. So Combining the two different tutorials I found that were outdated but each had a great way of doing part of what I needed I got this code that is cross browser compatible and works great to load jQuery or any script and then do something afterwards!
load = function() {
load.getScript("https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js");
}
// dynamically load any javascript file.
load.getScript = function(filename) {
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.setAttribute("onreadystatechange", "DOMLoaded()")
script.setAttribute("onload", "DOMLoaded()")
script.setAttribute("src", filename)
if (typeof script!="undefined")
document.getElementsByTagName("head")[0].appendChild(script)
}
load();
function DOMLoaded(){
// do jQuery(or whatever script you load) stuff here
};
Original Resources – somewhat outdated but good for ideas…
Tutorial #1
Tutorial #2
I found another script that is a great bookmarklet loading script but is too simple for many purposes:
javascript:scriptLocation=prompt('Script Location?');(function(){document.body.appendChild(document.createElement('script')).src=scriptLocation;})();