3

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?

3 Answers 3

4

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
})
Sign up to request clarification or add additional context in comments.

Comments

2
var checkvarint = setInterval(function(){
  if(swifttagdiv.firstChild.firstChild.src){
    varLoaded(); clearInterval(checkvarint);
  }
},10);

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

Comments

0

Mic's answer is great.
Here is the same thing only less abstracted, 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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.