jQuery.globalEval()


jQuery.globalEval( code )返回值: 任何类型

描述: 在全局范围内执行 JavaScript 代码。

此方法的行为与使用普通 JavaScript eval() 不同,因为它是在全局上下文中执行的(这对于动态加载外部脚本非常重要)。

示例

在全局上下文中执行脚本。

1
2
3
4
5
function test() {
jQuery.globalEval( "var newVar = true;" );
}
test();
// newVar === true

在启用了内容安全策略的网站上,使用 nonce 值执行脚本。

1
2
3
4
5
6
7
function test() {
jQuery.globalEval( "var newVar = true;", {
nonce: "nonce-2726c7f26c"
} );
}
test();
// newVar === true