jQuery.globalEval()
S2C Home « Utilities « jQuery.globalEval()
Global execution scoping.
Description
The jQuery.globalEval()
jQuery General utility method, allows us to execute some JavaScript code at global scope.
Shorthand version $.globalEval()
- The
jQuery.globalEval()
jQuery General utility method allows scripts to be executed in the global context allowing external scripts to be loaded dynamically:- What this means in practice is that the script becomes a property of the
window
object and is thus available in the global scope. - When using the
jQuery.ajax()
method and having thedataType
setting asscript
, an implicit call is made to thejQuery.globalEval()
jQuery General utility method to run the script in the global scope.
- What this means in practice is that the script becomes a property of the
Do not confuse the jQuery.globalEval()
with the JavaScript eval()
method. The eval()
method will only 'live' in the context of the scope it was 'called' in. Outside the
scope it was 'called' in the context is lost; apart from this the eval()
method is deemed unsafe.
Syntax
Signature | Description |
---|---|
jQuery.globalEval( code ) | Execute some JavaScript code at global scope. |
Parameters
Parameter | Description | Type |
---|---|---|
code | The JavaScript code to execute. | String |
Return
An Array
object.
jQuery.globalEval( code )
ExamplesTop
Execute some JavaScript code at global scope.
In the example below when we press left button we run the function globalEvalTest()
which uses the jQuery.globalEval()
jQuery General utility method to place a property on the window
object. We then access this variable outside the function scope and display a message showing the variable ourMessage
can be accessed globally.
When we press right button we run the function globalEvalTest2()
which uses the jQuery.globalEval()
jQuery General utility method to place a property on the window
object. We then use $.ajax()
to run an external JavaScript file url: "../js/test.js"
. within this external script we display the variable ourMessage2
as part of a
display a message showing the variable can be accessed globally.
$(function(){
$('#btn15').one('click', function(){
function globalEvalTest(){
$.globalEval("var ourMessage = '*** A message ***';");
}
globalEvalTest();
$('#div13').append('Can we access ourMessage globally? ' + ourMessage + '<br>');
});
$('#btn16').one('click', function(){
function globalEvalTest2(){
$.globalEval("var ourMessage2 = '*** Message 2 ***';");
}
globalEvalTest2();
$.ajax({
type: "GET",
url: "../js/test.js",
dataType: "script"
});
});
});
/*
* The code for the external Javascript file called from $.ajax() (url: "../js/test.js")
* is shown below.
*/
$(function(){
var someText = 'Some text to pass across ';
$('#div13').append('Message: ' + someText + ourMessage2 + '<br>');
});
div13. Some initial text.
Related Tutorials
jQuery Intermediate Tutorials - Lesson 9 - jQuery General Utilities