jQuery jQuery.globalEval() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Global exec

What You’ll Learn

The jQuery.globalEval() utility executes a JavaScript string in the global scope — unlike eval() inside a function. This tutorial covers syntax, official examples, scope comparisons, CSP nonce support, iframe context, security rules, and how jQuery uses it internally.

01

Syntax

$.globalEval(code)

02

Global

window scope

03

vs eval

Local scope

04

nonce

CSP 3.4+

05

doc

iframe 3.5+

06

Security

Trusted only

Introduction

Sometimes JavaScript must run from a string rather than a <script src> file — legacy AJAX responses, dynamically inserted HTML with inline scripts, or plugin bootstrapping. The challenge is scope: code run with plain eval() inside a function stays local to that function.

jQuery provides jQuery.globalEval() (also written $.globalEval()) to execute strings in the global context — the same place normal page scripts run. jQuery itself uses this when processing <script> tags in injected markup. Because it runs arbitrary code, treat it as a power tool: useful for learning and maintenance, dangerous with untrusted input.

Understanding the jQuery.globalEval() Method

jQuery.globalEval(code) takes a string of JavaScript and executes it so that var declarations and function definitions become globals — accessible as properties of window in browsers.

Since jQuery 3.4 you can pass { nonce: "..." } for Content Security Policy. Since jQuery 3.5 you can pass a doc argument to evaluate in an iframe’s document context.

⚠️
Security Warning

Never call globalEval with user-supplied or URL-parameter strings. That is a direct XSS vector. Use only trusted script content you control.

📝 Syntax

Three forms of jQuery.globalEval:

jQuery
// Basic (since jQuery 1.0.4)

jQuery.globalEval( code )



// With CSP nonce (since jQuery 3.4)

jQuery.globalEval( code, { nonce: "nonce-abc123" } )



// With target document (since jQuery 3.5)

jQuery.globalEval( code, options, doc )

Parameters

  • code — string of JavaScript to execute globally.
  • options (optional) — plain object; nonce for CSP-compliant scripts.
  • doc (optional) — document whose global context should run the code.

Return value

  • Generally undefined — side effects (globals, DOM changes) are the purpose.

Official minimal example

jQuery
function test() {

  jQuery.globalEval("var newVar = true;");

}

test();

// newVar === true (global)

⚡ Quick Reference

CallEffect
$.globalEval("var x = 1")Creates global x
eval("var x = 1") inside functionLocal x only
$.globalEval(code, { nonce })CSP nonce (3.4+)
$.globalEval(code, {}, iframeDoc)iframe context (3.5+)
User input stringNever pass — XSS risk
Empty / whitespace stringNo-op (jQuery skips)

📋 $.globalEval vs eval() vs <script>

Three ways to run code from strings — scope and safety differ.

$.globalEval
global scope

Dynamic script strings

eval()
local scope

Function-local vars

<script>
DOM tag

Preferred modern load

ES modules
import

Best for new apps

Examples Gallery

Each example uses trusted, hard-coded strings only — never replicate these patterns with user input. Open DevTools or use the Try-it links to run them interactively.

📚 Getting Started

Official jQuery API example — global variable from inside a function.

Example 1 — Official Global Variable Demo

From the jQuery documentation — newVar is global after globalEval.

jQuery
function test() {

  jQuery.globalEval("var newVar = true;");

}

test();



console.log(typeof newVar !== "undefined"); // true

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

How It Works

Even though globalEval is called inside test(), the var declaration runs in the global context — not the function’s local scope.

📈 Practical Patterns

Scope comparison, multi-line scripts, CSP, and modern alternatives.

Example 2 — globalEval vs eval() Scope

Same string, different scope — only globalEval leaves a global behind.

jQuery
function demo() {

  $.globalEval("var fromGlobalEval = 'global';");

  eval("var fromEval = 'local';");

  console.log(fromEval); // local — works here

}

demo();



console.log(typeof fromGlobalEval !== "undefined"); // true

console.log(typeof fromEval !== "undefined");       // false
Try It Yourself

How It Works

This is why jQuery uses globalEval for injected scripts — those scripts expect to define globals and register plugins on window.

Example 3 — Multi-Statement Script String

Execute several statements and define a global helper function.

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

Legacy AJAX loaders sometimes received multi-line script bodies from the server. globalEval runs the entire string as one global script block.

Example 4 — CSP nonce Option (jQuery 3.4+)

Official pattern for sites with Content Security Policy enabled.

jQuery
function test() {

  jQuery.globalEval("var cspVar = true;", {

    nonce: "nonce-2726c7f26c"

  });

}

test();

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

How It Works

When CSP blocks inline scripts, the nonce must match your policy. jQuery attaches it to the script element it creates internally when evaluating the string.

Example 5 — Prefer Safe Alternatives in New Code

Modern apps should load scripts explicitly — not from untrusted strings.

jQuery
// Avoid: $.globalEval(userInput) — XSS!



// Better: load a trusted file

function loadScript(src) {

  return $.getScript(src); // jQuery handles script element

}



// Best: ES modules in modern apps

// import { init } from './widget.js';



console.log("Use getScript or modules — not user strings");
Try It Yourself

How It Works

Understand globalEval to read jQuery internals and maintain legacy code — but default to $.getScript(), dynamic <script> tags, or ES modules for new features.

🚀 Common Use Cases

  • Injected <script> tags — jQuery internal use in .html() / .append().
  • Legacy AJAX script responses — execute returned JavaScript globally.
  • Plugin bootstrapping — define window-level APIs from strings.
  • iframe scripts — pass doc for child document context (3.5+).
  • CSP-compliant eval — pass nonce when policy requires it.
  • Reading jQuery source — understand dynamic script execution paths.

🧠 How jQuery.globalEval() Runs Code Globally

1

Validate string

Skip empty or whitespace-only code strings.

Input
2

Create script context

Build a script in the target document — attach nonce if provided.

Script
3

Execute globally

Run in global scope — not the caller’s local function scope.

Eval
4

Globals defined

Variables and functions become available on window (or iframe global).

📝 Notes

  • Available since jQuery 1.0.4 — nonce since 3.4, doc since 3.5.
  • Never pass user-controlled strings — treat as arbitrary code execution.
  • Differs from eval() — always global scope, not caller scope.
  • jQuery uses this internally when DOM methods encounter inline scripts.
  • Prefer $.getScript() or <script src> for loading external files.
  • CSP may block inline eval entirely — design policies accordingly.
  • Related: $.getScript(), DOMEval (internal), .html().

Browser Support

jQuery.globalEval() has been part of jQuery since jQuery 1.0.4+. It normalizes global script execution across browsers jQuery supports, including legacy IE via execScript.

jQuery 1.0.4+

jQuery jQuery.globalEval()

Supported in jQuery 1.x, 2.x, and 3.x. nonce (3.4+) and doc (3.5+) extend CSP and iframe support.

100% With jQuery loaded
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
jQuery.globalEval() Universal

Bottom line: Works wherever jQuery runs. Strict CSP policies may still block dynamic execution — use nonce or avoid eval patterns entirely.

Conclusion

The jQuery.globalEval() utility executes JavaScript strings in the global scope — the behavior injected <script> tags expect. It powers legacy dynamic loading and jQuery’s own DOM script handling.

Learn it to understand jQuery internals and maintain older codebases. For new projects, prefer $.getScript(), explicit script tags, or ES modules — and never feed user input into globalEval.

💡 Best Practices

✅ Do

  • Use only trusted, server-controlled script strings
  • Pass nonce when CSP requires it (jQuery 3.4+)
  • Pass doc for iframe script context (3.5+)
  • Prefer $.getScript() for external file loading
  • Understand scope difference vs eval()

❌ Don’t

  • Pass URL parameters, form input, or API responses blindly
  • Use globalEval for configuration — use JSON instead
  • Assume CSP allows eval on production sites
  • Define globals when modules would be cleaner
  • Copy legacy AJAX eval patterns into new apps

Key Takeaways

Knowledge Unlocked

Five things to remember about jQuery.globalEval()

Execute script strings in global scope.

5
Core concepts
📝 02

String

code arg

Input
🚫 03

eval

Local only

Compare
🔒 04

nonce

CSP

3.4+
⚠️ 05

Trust

No user input

Security

❓ Frequently Asked Questions

jQuery.globalEval(code) executes a string of JavaScript in the global scope — the same context as scripts loaded in the page head. Variables and functions declared by the string become globals (on window in browsers).
eval() runs code in the current lexical scope — variables stay local inside a function. globalEval() always runs in the global context, which is required when dynamically loading scripts that must define window-level APIs.
jQuery calls globalEval when processing inline script tags inserted through DOM manipulation — for example .html() or .append() with <script> blocks, and when executing scripts from AJAX responses in legacy patterns.
No. Never pass untrusted strings to globalEval — it is equivalent to running arbitrary code and enables XSS attacks. Only use trusted, server-controlled script content, and prefer modern alternatives like ES modules or explicit script elements.
Since jQuery 3.4, you can pass { nonce: "..." } as the second argument so the executed script carries a CSP nonce attribute — required on sites with strict Content Security Policy rules for inline scripts.
jQuery.globalEval(code, options, doc) accepts a document object so code runs in that document's global context — useful for scripts inside iframes where the top-level window is the wrong scope.
Did you know?

Early jQuery versions used window.execScript on Internet Explorer and window.eval.call(window, code) elsewhere — both tricks force global scope. That cross-browser normalization is exactly why globalEval exists instead of raw eval() in jQuery’s DOM manipulation pipeline.

Next: jQuery.support Property

Understand jQuery’s internal browser flags — and why not to use them in app code.

jQuery.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.

6 people found this page helpful