如何在Blackberry浏览器上动态添加脚本元素?

时间:2011-01-24 14:58:32

标签: javascript events dom browser blackberry

我在blackberry9300(5.0.0.832)。我试图以编程方式添加一个javascript元素。

var script=document.createElement('script');
script.src='file.js';
script.type='text/javascript';
script.onload=function(){alert('loaded');}; //Nothing happens
script.addEventListener('load', function(){alert('loaded');}, false); //Nothing happens
script.addEventListener('readystatechange', function(){alert('state changed');}, false); //Nothing happens
script.onreadystatechange=function(){alert('state changed')}; //Nothing happens
document.getElementsByTagName('head').item(0).appendChild(script);
有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:3)

旧版操作系统上的黑莓浏览器(< 6.0)不会触发onload事件或不会更改脚本的readyState。所以我需要轮询js文件是否成功加载。如果有人感兴趣,这是该功能。

function loadScript(path,callback,chkvar){
  var a=document.createElement('script');
  a.src=path;
  a.type='text/javascript';
  a.onreadystatechange=function(){
    if(this.readyState=='complete'||this.readyState=='loaded')
      callback();
  };
  a.onload=callback;
  if(a.hasOwnProperty('onload')==false)
    var e=setInterval(function(){
      if(eval(chkvar)){  //chkvar will only be available after js file is loaded.
        clearInterval(e);
        callback();
      }
    },50);
  }
  document.getElementsByTagName('head').item(0).appendChild(a);
}