jQuery API

jQuery.globalEval()

jQuery.globalEval( code )

Description: Execute some JavaScript code globally.

  • version added: 1.0.4jQuery.globalEval( code )

    codeThe JavaScript code to execute.

This method behaves differently from using a normal JavaScript eval() in that it's executed within the global context (which is important for loading external scripts dynamically).

Example:

Execute a script in the global context.

function test(){
    jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true

Support and Contributions

Need help with jQuery.globalEval() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.globalEval()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://elrafa.0fees.net/ rafael

    what is a good use case for this, doesn’t this go against Doug Crockford’s “eval is evil” principle.

  • http://www.learningjquery.com/ Karl Swedberg

    It doesn’t actually use eval()

  • Anonymous

    I have read the codes of globalEval().
    head.insertBefore(script, head.firstChild) if one line of its source code.
    Somebody says code in script node loaded through ajax will not run automaticlly.
    But why this works?
    Please help me with this question.

  • Alan_chen222

    Does this function return sth?
    When I need the eval result, how can I get it?

  • Sinsedrix

    Could you just give an example of how to load “external scripts dynamically” ?
    Where should it be added (head, body, wherever) ?
    Will these scripts be debuggable ? How ?
    No answer found on forum… Thanks in advance.

  • Sinsedrix

    Could you just give an example of how to load “external scripts dynamically” ?
    Where should it be added (head, body, wherever) ?
    Will these scripts be debuggable ? How ?
    No answer found on forum… Thanks in advance.