Access variable from dynamically loaded external javascript file

I have an external loaded js file (which I cannot change) with document.createElement (), and I need to access the variable from it. The problem is that I do not know when it will finish the download. I tried the jQuery document ready function, but it seems to be deployed earlier than the javascript file. I can access a variable like this:

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

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

+3
source share
3 answers

You can enter a script using Javascript instead of putting it on your page. This way you can control when it is loaded.

, :

    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){
   //your code here
})
+4
var checkvarint = setInterval(function(){
  if(swifttagdiv.firstChild.firstChild.src){
    varLoaded(); clearInterval(checkvarint);
  }
},10);

function varLoaded(){
    alert("LOADED!");
    alert(swifttagdiv.firstChild.firstChild.src);
}
+2

The answer to the microphone is great.
Here is the same thing that is less abstract, perhaps it will be instructive

var scriptElement = document.createElement( 'script' );
scriptElement.type = "text/javascript";
scriptElement.src  = "https://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core-debug.js";

function loadHandler() {
    alert( 'loaded' );
}

// for ie
scriptElement.onreadystatechange = function () {
    if( this.readyState == 'complete' ){
        loadHandler();
    }
}
// for others
scriptElement.onload= loadHandler;

document.getElementsByTagName('head')[0].appendChild( scriptElement );
0
source

All Articles