• Login
  • login to access premium content (it's free).

dynamically loaded javascript

I was starting to get a lot of jQuery plugins on WebBlocks.co the CMS that runs learnhtmlos.com. They were all needed but only in certain contexts. I found these 3 articles useful. I rolled them into my own safe code execution script.

Start by specifying a global Javascript variable like jQuery.colorbox and its url and the code you want to run. If the url is already loaded it will execute the code, if not it will load url then execute the code.

The ridiculous case of adding a script element

Check if a jQuery plugin is loaded

Dynamically load js inside js

The script

runSafe=function(name,url,callback){
 if(typeof window[name] != 'undefined'){
  callback;
 } else {
  var js = document.createElement('script');
  js.src = url;
  js.onload = js.onreadystatechange = callback;
  var first = document.getElementsByTagName('script')[0];
  first.parentNode.insertBefore(js, first);
 }
}

Usage

runSafe('jQuery.colorbox', '/apps/scripts/colorbox.min.js',function(){

 // do something with the colorbox plugin

});