关于window.execScript的兼容性问题与解决办法

最先知道的一个是window.eval函数,后来又知道IE下有个window.execScript。其实这两个函数有很大区别的。

先举个例子吧

 demo1:

var globalV =123;
function testEval(){   
    eval(" var globalV = 'global' ");
}  
testEval();
alert(globalV); //弹出123,ie与ff都如此

demo2:

var globalV =123;
function testEval(){   
    execScript(" var globalV = 'global' ");
}  
testEval();
alert(globalV); //IE弹出global,ff下没有execScript方法

那么如何解决execScript的兼容性问题呢。今天看了mootools的源码发现了一种比较好的解决办法

var exec=function(text){
 if (!text) return text;
 if (window.execScript){
  window.execScript(text);
 } else {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.text = text;
  document.head.appendChild(script);
  document.head.removeChild(script);
 }
 return text;
}

就是动态插入与删除一段js代码,这样就可以保证代码在全局空间里执行了,这种方法其实之前也在Jquery的源码中见到,实现原理一样

// Evalulates a script in a global context
 globalEval: function( data ) {
  if ( data && rnotwhite.test(data) ) {
   // Inspired by code by Andrea Giammarchi
   // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
   var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement,
    script = document.createElement( "script" );

   if ( jQuery.support.scriptEval() ) {
    script.appendChild( document.createTextNode( data ) );
   } else {
    script.text = data;
   }

   // Use insertBefore instead of appendChild to circumvent an IE6 bug.
   // This arises when a base node is used (#2709).
   head.insertBefore( script, head.firstChild );
   head.removeChild( script );
  }
 },

我也想到了一个比较简洁的方法

var exec=function(text){

  if(window.execScript){

     window.execScript(text);

     return  text;

  } 

  window.eval.call(window,text);//利用call来改变eval执行的环境,但此方法在ie中无效,不知道为啥

    return  text;

}

原来eval和window.eval是不同的,惭愧现在才明白

var exec=window.execScript || function(statement) {
    
    // 如果正常浏览器,使用 window.eval
    return window.eval(statement);
   },

转载于:https://www.cnblogs.com/hust/archive/2011/04/24/2026200.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值