Skip to content

Web2Coder

My Desktop Blog News Articles Tutorials Links Forum
You are here: Home arrow Blog arrow Dynamically Loading external JavaScript file
Dynamically Loading external JavaScript file Print E-mail
Written by Administrator   
Tuesday, 10 April 2007
Tag it:
Stumble
Delicious
Digg
feedmelinks
Reddit
YahooMyWeb
Spurl
Technorati

As a web designer you may face a problem of how to dynamically insert JavaScript inside your web pages. Since Dynamic Object Model is now getting more popular among web designers, It is important to find a good way for Inserting or even executing JavaScript  dynamically inside web pages. There are different ways for dynamically inserting or executing several JavaScript inside your web page.

This is a function for appending a child to the parent element which is here body. 

 

function loadinlinescript(){
var objhead = window.document.getElementsByTagName('body')[0];
var objscript = window.document.createElement('script');
objscript.text = ajax.responseText;
objscript.type = 'text/javascript';
objhead.appendChild(objscript);
}

 

Dynamic Javascript Insertion

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/services/feeds/photos_public.gne?tags=sunset&format=json';
headID
.appendChild(newScript);

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

Adding Javascript Through Ajax

On your own site and domain you can use dynamic script loading to keep the size of your javascripts small and serve only what the user actually needs, as the scripts are needed. You should of course use AJAX ( responseText ) to retrieve JSON formated data and Javascripts off your own site instead of dynamic <script> attachment. Here's an example of an ajax object which will load a javascript file then pass it through the eval command (which is basically just the javascript compiler). After this is done the functions and variables will be available to the other functions in your web page.

function ajaxObject(url, callbackFunction) {
 
var that=this;      
 
this.updating = false;

 
this.update = function(passData,postMethod) {
   
if (that.updating==true) { return false; }
    that
.updating=true;                      
   
var AJAX = null;                          
   
if (window.XMLHttpRequest) {              
      AJAX
=new XMLHttpRequest();              
   
} else {                                  
      AJAX
=new ActiveXObject("Microsoft.XMLHTTP");
   
}                                            
   
if (AJAX==null) {                            
     
return false;                              
   
} else {
      AJAX
.onreadystatechange = function() {  
       
if (AJAX.readyState==4) {            
          that
.updating=false;                
          that
.callback(AJAX.responseText,AJAX.status,AJAX.responseXML);        
         
delete AJAX;                                        
       
}                                                      
     
}                                                        
     
var timestamp = new Date();                              
     
if (postMethod=='POST') {
       
var uri=urlCall+'?'+timestamp.getTime();
        AJAX
.open("POST", uri, true);
        AJAX
.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        AJAX
.send(passData);
     
} else {
       
var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1);
        AJAX
.open("GET", uri, true);                            
        AJAX
.send(null);                                        
     
}              
     
return true;                                            
   
}                                                                          
 
}
 
var urlCall = url;        
 
this.callback = callbackFunction || function () { };
}  

function attachScript(responseText, responseStatus) {
   
// This function is called by the ajaxObject when the server has finished
         
// sending us the requested script.
   
if (responseStatus==200) {
           
eval(responseText);
         
}
}

// ajaxObject is an object constructor, pass it the server url you want it to call
// and the function name you want it to call when it gets the data back from the server.
// Use the .update() method to actually start the communication with the server.
// The first optional argument for update is the data you want to send to the server.
// ajaxvar.update('id=1234&greed=good&finish=true');
// The second optional argument for update is 'POST' if you want to send the data
// as a POST instead of the default GET (post can handle larger amounts of data and
// the data doesn't show up in your server logs).
// ajaxvar.update('id=1234&greed=good&finish=true','POST');

var getScriptViaAjax=new ajaxObject('http://mydomain.com/somescript.js',attachScript);
    getScriptViaAjax
.update();
var anotherScript = new ajaxObject('http://mydomain.com/anotherScript.php',attachScript);
    anotherScript
.update('userId=4323','POST');

It's important to note that we don't need a server-side script here. When we create our ajaxObject we pass it the url of a javascript file which is the exact same as any file you'd set up as an external <script>. The ajaxObject will retrieve the file then pass it to attachScript which then passes the file through eval which executes it exactly as if it were being loaded in via the <script> tag. You can call a script if you want and have php or some other server-side scripting language generate custom, dynamic javascript on the fly, but you can also call a static javascript file as well.

Trackback(0)
Comments (5)Add Comment
good info
written by AD, October 18, 2007
Thanks , nice codes "Dynamic Javascript Insertion"
توکلی جان دستت درد نکنه
written by Casitecenter, March 05, 2008
توکلی جان دستت درد نکنه
واقعا افتخار بايد کرد به جوان هايی مثل شما
بی نظير ترين اجکس واسه جملا همينه که نوشتی منتظر نسخه های جديدش هستيم
Awesome - but I have an issue
written by Fahd, March 07, 2008
Everything is working just fine EXCEPT the functions in my JS file are not being recognized, but code that isn't in a function is fine. Firebug keeps saying its "not defined". It seems like its just not being eval-ed, or maybe its something else. Any solution?
Any Demos?
written by Ken, October 08, 2008
I know just enough AJAX do be dangerous... have a demo on how to use this code?

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley
Smiley

security code
Write the displayed characters


Copyright 2007. All Rights Reserved.
busy
Last Updated ( Friday, 28 September 2007 )
 
< Prev

Login


[+]
  • Narrow screen resolution
  • Wide screen resolution
  • Auto width resolution
  • Increase font size
  • Decrease font size
  • Default font size
  • fresh color
  • hot color
  • natural color
  • dark color