jQuery globalEval() Method

Beginner
7 min read
Updated: Oct 2026
4 examples
Live preview

What Is globalEval()?

jQuery.globalEval(code) (alias $.globalEval) executes a JavaScript string in the global scope (since jQuery 1.0.4). Unlike eval(), declarations become true globals — important when loading scripts dynamically.

Remember
$.globalEval(code)                    // jQuery 1.0.4+
$.globalEval(code, { nonce: "..." })  // jQuery 3.4+ (CSP)
$.globalEval(code, options, doc)      // jQuery 3.5+ (iframe doc)

function test() {
  $.globalEval("var newVar = true;");
}
test();
// newVar === true  (global!)
NeedUse
Run trusted script string globally$.globalEval(code)
Load a remote .js file$.getScript(url)
Local scope onlyeval(code) (different tool)

How to Use globalEval()

Pass a trusted code string; optionally add CSP nonce or a target document.

  1. Start with a trusted JavaScript string (never user input).
  2. Call $.globalEval(code) so var / function declarations land on the global object.
  3. On CSP sites (jQuery 3.4+), pass { nonce: "..." } as the second argument.
  4. For iframes (jQuery 3.5+), pass the iframe’s contentDocument as the third argument.
PieceRequired?Role
codeYesJavaScript string to execute globally
options.nonceNo (3.4+)CSP nonce for the injected script
docNo (3.5+)Document whose global context runs the code
Return—Result of the last expression (Anything)

Pseudocode

Pseudocode
function globalEval(code, options, doc):
    targetDoc = doc or current document
    // run code in targetDoc's global scope
    // (not the calling function's local scope)
    return result of last expression

// Official pattern:
function test():
    $.globalEval("var newVar = true;")
test()
// newVar is now a global → true

Cheat Sheet

Keep these facts handy while working with global script strings.

TopicDetail
SyntaxjQuery.globalEval(code[, options][, doc])
Since1.0.4 · nonce 3.4 · doc 3.5
ScopeGlobal (unlike eval())
SecurityTrusted code only — XSS risk
CSP{ nonce: "..." } (3.4+)
IframePass contentDocument as doc (3.5+)
Remote files$.getScript()

Live Preview

Pick a trusted sample string and run it with $.globalEval.

Browser demo of $.globalEval() — same idea as the examples below. Demo code is fixed (not user-typed).

Result
sample = Create global flag
code = "var geLiveFlag = true;"
geLiveFlag → true

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Official Global Flag

Create a global variable from inside a function.

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

console.log(typeof newVar);  // "boolean"
console.log(newVar);         // true
Try It Yourself

How It Works

  1. Call from a function. test() shows the code is not running at top level.
  2. Run globally. jQuery.globalEval("var newVar = true;") defines newVar on the global object.
  3. After return. The variable still exists — it is not local to test.
  4. Read it. typeof newVar is "boolean" and the value is true.

Example 2 — globalEval vs eval()

Same string, different scope rules.

jQuery
function demo() {
  $.globalEval("var fromGlobalEval = 'global';");
  eval("var fromEval = 'local';");
}
demo();

console.log(typeof fromGlobalEval);  // "string"
console.log(typeof fromEval);        // "undefined"
Try It Yourself

How It Works

  1. globalEval. var fromGlobalEval is attached to the global object.
  2. eval. var fromEval stays inside demo() and disappears when the function ends.
  3. Check types. After demo(), only fromGlobalEval exists.
  4. Takeaway. Use globalEval when dynamic code must define page-level APIs.

Example 3 — Multi-Statement Global Helper

Define a small counter API from one script string.

jQuery
var script = [
  "window.demoCounter = 0;",
  "window.incrementDemo = function () {",
  "  window.demoCounter++;",
  "  return window.demoCounter;",
  "};"
].join("\n");

$.globalEval(script);

console.log(incrementDemo());  // 1
console.log(incrementDemo());  // 2
Try It Yourself

How It Works

  1. Build the string. Several statements joined with newlines — still one code argument.
  2. Attach to window. Counter and function are explicit globals.
  3. Evaluate once. $.globalEval(script) installs both names.
  4. Call later. incrementDemo() works from normal page code after evaluation.

Example 4 — CSP nonce Option

Official jQuery 3.4+ pattern for Content Security Policy sites.

jQuery
function test() {
  jQuery.globalEval("var cspVar = true;", {
    nonce: "nonce-2726c7f26c"
  });
}
test();

console.log(cspVar);  // true
Try It Yourself

How It Works

  1. Second argument. Pass a plain object with nonce (jQuery 3.4+).
  2. CSP match. The value must match your page’s Content-Security-Policy nonce.
  3. Same global result. The string still runs globally — cspVar becomes true.
  4. This demo. No CSP header here; the option is shown for real locked-down sites.

Edge Cases & Pitfalls

Check these before evaluating dynamic script strings.

security

Untrusted strings = XSS

Treat globalEval like running raw code. Never pipe form fields, URL params, or third-party HTML into it.

scope

let / const are not window props

Global var and function attach to window. Top-level let/const in script scope behave differently — prefer explicit window.name = ... when you need a clear global.

csp

Strict CSP needs a nonce

Without a matching nonce, browsers may block the injected script. Pass { nonce } on jQuery 3.4+ when your policy requires it.

prefer

Prefer modules or getScript

For remote files use $.getScript(). For modern apps, ES modules are clearer than string evaluation.

Browser Support

jQuery.globalEval() needs a browser document. Available since jQuery 1.0.4+ (nonce in 3.4+, doc in 3.5+) in all modern browsers — not for Node.js, Bun, or Deno.

✓ jQuery 1.0.4+ · Browsers only

jQuery.globalEval()

Works in Chrome, Firefox, Safari, Edge, and other browsers with jQuery loaded. Use nonce (3.4+) and doc (3.5+) only on matching jQuery versions.

100% Browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
$.globalEval() Browsers

Bottom line: Use $.globalEval(code) in the browser with trusted strings only. Load remote scripts with $.getScript() when you have a URL.

Performance Notes

ApproachCostBest for
$.globalEval(code)Parse + run onceSmall trusted snippets
Repeated globalEvalRe-parse each timeAvoid in hot loops
$.getScript(url)Network + parseExternal .js files

Parsing a string every time is slower than calling a normal function. Evaluate once, then call the globals you defined — do not re-run large strings on every click or animation frame.

Key Takeaways

  • Role: $.globalEval(code) runs a string in global scope.
  • vs eval: globals survive; eval locals do not.
  • CSP: pass { nonce } on jQuery 3.4+ when required.
  • Safety: trusted code only — never user input.

One line: use $.globalEval only for trusted script strings that must become true globals — prefer $.getScript or modules when you can.

Frequently Asked Questions

jQuery.globalEval(code) executes a string of JavaScript in the global scope — the same context as scripts in the page. Variables and functions declared with var or function in that string become globals (on window in browsers).
eval() runs in the current lexical scope, so var declarations inside a function stay local. globalEval() always runs in the global context, which matters when dynamically loading scripts that must define window-level APIs.
jQuery uses it when processing inline script tags inserted through DOM APIs — for example .html() or .append() with script blocks — so those scripts run globally like normal page scripts.
No. Never pass untrusted strings — it runs arbitrary code and enables XSS. Only use trusted, server-controlled script content. Prefer $.getScript() for remote files or ES modules for modern apps.
Since jQuery 3.4, pass { nonce: "..." } as the second argument so the executed script carries a CSP nonce — required on sites with a strict Content Security Policy for inline scripts.
jQuery.globalEval(code, options, doc) accepts a Document so code runs in that document's global context — useful for scripts inside iframes where the top-level window is the wrong scope.
No. It targets a browser document (and optional iframe Document). Use Node's own module system or vm APIs on the server — not jQuery.globalEval.

Next: jQuery.support

See why jQuery’s internal feature flags should not drive app code.

support tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful