« A Solution: Playing... | Main | Mirage - Open Source... »
http://blogs.sun.com/insidemyhead/date/20070626 Tuesday June 26, 2007

Dynamic JavaScript Loading

While developing a custom jMaki widget we came across a problem in which we needed to load a javascript dynamically from another javascript file. There are atleast 2 ways I know this can be done. Here is one such method.

 

function jsinclude( jscriptfile )
{

// create a script node
var s = document.createElement('script');
s.src = jscriptfile;
s.type = "text/javascript";

// add it to the node called 'SOMEPARENT'.. it could be the HEAD node of the html page as below....

document.getElementsByTagName('head').item(0).appendChild(s);
}

Calling this function in your javascript you can load as many JS files as needed and embed them into your current DOM tree as follows :


jsinclude('dojofunctions.js');




Posted by insidemyhead [Sun] ( June 26, 2007 09:21 AM ) Permalink | Comments[4]
Comments:

Hi Sandeep,

jMaki has two built in functions that will load scripts in the same way and as an added bonus allow you to attach a callback that will be fired when the script has finished loading (a very hard thing to get right).

The function for a singe script is:

jmaki.addLibrary(url, callback);

Will load the script and fire the callback. For loading a group of scripts with a single callback.

jmaki.addLibraries(url string array, callback);

Both these functions are used heavily internally in jMaki and work very well. They also clean up script element references once the scripts have loaded.

Enjoy!

-Greg

Posted by Greg Murray on June 26, 2007 at 01:06 PM IST #

Thanks Greg!

Posted by Sandeep Soni on June 26, 2007 at 08:35 PM IST #

Found a typo: document.createlement should be document.createElement

Posted by Greg Reimer on June 27, 2007 at 01:31 AM IST #

Thanks Gregory for pointing out. I corrected the typo.

Posted by Sandeep Soni on June 27, 2007 at 11:23 AM IST #

Post a Comment:
  • HTML Syntax: NOT allowed