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"></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



