Mar 8, 2010

jQuery.globalEval

$.globalEval utility is a useful function, because it is preferred compare with eval in calling ajax script. What it does is adding script tag to document, then remove it later.

globalEval: function( data ) {
 if ( data && rnotwhite.test(data) ) {
  // Inspired by code by Andrea Giammarchi
  // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
  var head = document.getElementsByTagName("head")[0] || document.documentElement,
   script = document.createElement("script");

  script.type = "text/javascript";

  if ( jQuery.support.scriptEval ) {
   script.appendChild( document.createTextNode( data ) );
  } else {
   script.text = data;
  }

  // Use insertBefore instead of appendChild to circumvent an IE6 bug.
  // This arises when a base node is used (#2709).
  head.insertBefore( script, head.firstChild );
  head.removeChild( script );
 }
},

$.globalEval("document.write('<h1>hello</h1>');");