Decoding jQuery – $.globalEval: Evaluates a script in a global context

In the Decoding jQuery series, we will break down every single method in jQuery, to study the beauty of the framework, as an appreciation to the collective/creative geniuses behind it.

jQuery.globalEval()
jQuery has a method jQuery.globalEval( code ), the difference between this method and a default JavaScript eval() is that globalEval is executed within the global context which is important for loading external scripts dynamically and use on a global level.

The jQuery source code

The source code looks like below:

globalEval: function( data ) {
  if ( data && rnotwhite.test( data ) ) {
    // We use execScript on Internet Explorer
    // We use an anonymous function so that context is window
    // rather than jQuery in Firefox
    ( window.execScript || function( data ) {
      window[ "eval" ].call( window, data );
    } )( data );
  }
}

Jim Driscoll found out that for more standards-respecting browsers, you could use eval.call(window,data), but for Chrome and IE, things are a bit different.

Internet Explorer:
It seems that IE uses window.execScript(data)

Chrome:
eval.call(window,data) breaks on Chrome, but window[ "eval" ].call( window, data) works on Chrome, and as well as other non-IE browsers, this is how the above workarounds based upon.

Here is a simple test:

<div id="log">&#60;/div>
<script>
function test(){
  jQuery.globalEval("var drinkType = 'absinthe';")
}
test();
if (drinkType == 'absinthe') {
  $('#log').html('live healthly, drink ' + drinkType+'');
}
</script>

Reference:
jQuery source on github: https://github.com/jquery/jquery/blob/master/src/core.js#L571
Jim Driscoll’s article: http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

About Shi Chuan

I am a web developer.
This entry was posted in JavaScript and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">