Welcome Message

"The difference between a successful person and others is not a lack of strength,
not a lack of knowledge, but rather a lack in will."
-Vince Lombardi

July 20, 2009

Dynamic Javascript Insertion using javascript

Fortunately, dynamic insertion of CSS or Javascript is relatively painless.

var headID = document.getElementsByTagName("head")[0];               
var newScript = document.createElement('script');                   
newScript.type = 'text/javascript';                                 
newScript.src = 'http://www.somedomain.com/somescript.js';          
headID.appendChild(newScript);                                      
               

It's really that simple. headID gets the <head> element of the page. Next we create a new 'script' element, assign it a text/javascript type, and then the url of the script (which can be anywhere on the net since it's basically a javascript include). Finally we append the new element to our head section where it is automatically loaded.

If you're loading an external javascript and you need to know when the script has loaded you can simply use .onload=yourfunction; to set up the onload handler. Here's an example.

var headID = document.getElementsByTagName("head")[0];                
var newScript = document.createElement('script');                   
newScript.type = 'text/javascript';                                 
newScript.onload=scriptLoaded;                                      
newScript.src = 'http://api.flickr.com/?tags=sunset&format=json';   
headID.appendChild(newScript);                                      

Now when this script has been loaded the .onload event will call a function named scriptLoaded().

 

No comments:

Post a Comment

Thank you for your valuable comments.