jQuery unveiled: the globalEval() method

The globalEval() method is used internally by jQuery to evaluates scripts in a global context. It's been inspired by a post of Andrea Giammarchi. It is as follows:

// Evalulates a script in a global context
 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 );
  }
 },
  1. creates a script element through the W3C DOM createElement method
  2. appends the newly created script to the head element by using the W3C DOM insertBefore instead of appendChild to circumvent an IE6 bug.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.