从动态加载的外部javascript文件访问变量 [英] accessing a variable from dynamically loaded external javascript file
问题描述
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屋!