Dynamically Load JavaScript Files and Execute Function

Source: http://unixpapa.com/js/dyna.html

The trick is to give the same name to the script loading function and the function that needed to be executed. Then when first clicked it will load the JS file and excute function because of the function  execute line in loaded JS. After that the JS loading function will get overridden by the loaded function.

 <input type="button" onclick="helper()" value="Helper">

   function helper()
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.type= 'text/javascript';
      script.src= 'helper.js';

The script file being loaded looks something like this:

   function helper()
     lots of code

   more function and global variable definitions


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: