从动态加载的外部javascript文件访问变量 [英] accessing a variable from dynamically loaded external javascript file

查看:88
本文介绍了从动态加载的外部javascript文件访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部的js文件被加载(我不能修改)与document.createElement(),我需要从它访问一个变量。问题是,我不知道什么时候完成加载。我尝试了jQuery的文档就绪功能,但它似乎比javascript文件更快地部署。我可以通过以下方式访问变量:

  setTimeout(console.log(swifttagdiv.firstChild.firstChild.src) ,5000); 

但这只是一个测试,看看变量是否是全局的。任何想法?

解决方案

您可以使用Javascript注入脚本,而不是将其放在页面中。这样,您可以控制何时加载。



这是一个动态地在页面中注入代码的功能:

  function inject(src,cb,target){
target = target || document.body的;
var s = document.createElement('SCRIPT');
s.charset ='UTF-8';
if(typeof cb ==='function'){
s.onload = function(){
cb(s);
};
s.onreadystatechange = function(){
(/loaded|complete/).test(s.readyState)&& CB(S);
};
}
s.src = src;
target.appendChild(s);
return s;
}

使用它:

  inject('/ path / to / file.js',function(script){
//你的代码在这里
})


I have an external js file being loaded (which I cannot modify) with document.createElement() and I need to access a variable from it. The problem is, I don't know when does it finish loading. I tried jQuery's document ready function but it seems to deploy sooner than the javascript file. I am able to access the variable like this though:

setTimeout("console.log(swifttagdiv.firstChild.firstChild.src)", 5000);

but this is just a test to see if the variable is global. Any ideas?

解决方案

You can inject the script by using Javascript instead of putting it in your page. This way you can control when it is loaded.

Here's a function I use to inject code in pages dynamically:

    function inject(src, cb, target){
        target = target || document.body;
        var s = document.createElement('SCRIPT');
        s.charset = 'UTF-8';
        if(typeof cb === 'function'){ 
            s.onload = function(){
                cb(s);
            }; 
            s.onreadystatechange = function () {
                (/loaded|complete/).test(s.readyState) && cb(s);
            };                     
        }
        s.src = src;
        target.appendChild(s);
        return s;
    }

to use it:

inject('/path/to/file.js', function(script){
   //your code here
})

这篇关于从动态加载的外部javascript文件访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆