miércoles, 23 de noviembre de 2011

Load javascript or css dynamically in javascript

Loading Javascript or CSS dynamically in a DOM with pure JavasScript

If for some reason you need to programatically load some javascript or css stylesheet in the document, here is some code that helped me and seems to work fine in most browsers.

/**
 * loads javascript file or css stylesheet in current document. Usage Examples:
 * loadFile("www.server.com/file1.js", "js", function(){ alert("file1.js
 * loaded!"); });
 * 
 * @param name :
 *            the url of the resource to load. I think there is no cross site
 *            problems here.
 * @param type :
 *            "js" or "css". if "js" then a new javascript script will be loaded
 * @param listener
 *            an optional function that will be called when loading of the
 *            resource is ready.
 * @author: sgurin
 */
var _loadF = function(name, type, listener) {
 var el = null;
 if (type == "js") {
  el = document.createElement("script");
  el.setAttribute("type", "text/javascript");
  if (listener) {
   el.onreadystatechange = function() {
    if (this.readyState == 'complete')
     listener();
   };
   el.onload = listener;
  }
  el.setAttribute("src", name);
 } else if (type == "css") {
  el = document.createElement("link");
  el.setAttribute("rel", "stylesheet");
  el.setAttribute("type", "text/css");
  el.setAttribute("href", name);
 }
 document.body.appendChild(el);
}

An example usage:

_loadF("http://code.jquery.com/jquery-2.0.0.min.js", "js", function(){
 //jquery loaded to current DOM window and ready to use
 $("p").click(function(e){
  alert("p clicked"); 
 });
}); 

Example where this can be useful

Some exentric programmers / web application need a javascript application to be loaded into the current document. This is often accomplished setting current web address to a "javascript: " prefixed address that execute some javascript code in the context of the current document or using firebug / chrome development console.

In this modality, the given javascript code will execute in the context of the current document, being able to show new visual components or even modify the current document. Here it is nice to have a short function that is capable of loading both javascript or css into the current DOM so we can use these libraries in this kind of programs.

Other example, paste the folowing into firebug/chrome devel console:

var _loadJs = function(name, listener) {
 var el = document.createElement("script");
 el.setAttribute("type", "text/javascript");
 if (listener) {
  el.onreadystatechange = function() {
   if (this.readyState == 'complete')
    listener();
  };
  el.onload = listener;
 }
 el.setAttribute("src", name);
 document.getElementsByTagName("head")[0].appendChild(el);
}; 
_loadJs("http://code.jquery.com/jquery-1.9.1.min.js", function(){
 alert("this document has "+$("p").size()+" paragraphs. "); 
}); 

No hay comentarios: