javascript - trick to evaluate javascript code in global scope

本文介绍了一种在所有浏览器中都能可靠地在全局作用域执行JavaScript代码的方法:通过创建新的script元素,注入要执行的代码,然后迅速将该script元素插入并从文档中移除。此外,还提供了一个使用jQuery实现的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

the reason why we have a dedicated session to have the tick to evaluete some javascript code inthe global context is that "The built-in methods for code evaluation are spotty, at best."

 

 It is a prooven practise , so that it is also a fool-proof way to execute code in the global scope, across all browsers , is to create a fresh script element, inject the code you wish to execute inside the script, and then quickly inject and remove the script from the document. 

 

 

below shows the method that demonsrate this technique 

 

 

/**************************************
*@Summary
*  this code is about to execute the script in the global context.  
*
* 
* the built-in methods for code evaluation are spotty, at best. THe one fool-proof way to execute code in the global scope, across all browsers, is to create a fresh script element, inject the code you wish 
* to execute inside the script, and then quickly inject and remove the script from the document.
* 
* this trick turns out to be very effective across many browsers.
*
*
***************************************/

function globalEval(data) {
  data = data.replace(/^\s+|\s+$/g, "");
  if (data) {
    var head = document.getElementsByTagName("head")[0] || document.documentElement,
      script = document.createElement("script");
    script.type = "text/javascript";
    script.text = data;
    header.insertBefore(script, head.firstChild);
    head.removeChild(script);
  }
}
 

 

Though I am not quite familiar with the JQuery libraries, but I think you can use the following code to dynamically load and executing some code on demand(the code may be downloaded fromthe server)\.

 

 

/**
* @Comment
*  the code below shows the possible way to do the 
*/
function evalScript(elem) {
  if (elem.src) {
    jQuery.ajax({
      url: elem.src,
      async: false,
      dataType: "script"
    });
  } else {
    jQuery.globalEval(elem.text || "");
  }
  if (elem.parentNode)
     elem.parentNode.removeChild(elem);
}
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值