javascriptjquerydynamic-script-loading

Javascript: Dynamically added script can't find previously defined function in another script


I'm having what seems to be a really simple issue that I really can't find a solution for:

In my code I have a script loaded in the header:

<script type="text/javascript" src="../js/viewdoc/index.js?v=1.33"></script>

In that specific script I declare the functions:

function addResizeListener(listener){
    //Attach the back button function to window resize event
    if(window.attachEvent) {
        window.attachEvent('onresize', listener); //Old browsers
    }
    else if(window.addEventListener) {
        window.addEventListener('resize', listener, true); //New browsers
    }
}

and:

function removeResizeListener(listener){
    //Remove the listener for the back button
    if(window.detachEvent) {
        window.detachEvent('onresize', listener);
    }
    else if(window.removeEventListener) {
        window.removeEventListener('resize', listener, true);
    }
}

then I load this file into the element with a loaderdoc id:

if ($('#loaderdoc').is(':empty')){
    $('#loaderdoc').load('../viewdoc/welcome.php');
}

I use the function addResizeListener to bind a function to the window resize event, this works perfectly, and the index.js script ends.

In the end of the loaded file welcome.php i added the line

<script src="../js/viewdoc/welcome.js"></script>

welcome.js is a script that uses the functions removeResizeListener and addResizeListener, but I get the error: Uncaught ReferenceError: addResizeListener is not defined

Why is this? Wasn't the functions defined and loaded before the script was added to the document?

Sorry if this was answered before, I just couldn't really find it, or maybe I don't know he right way to search for it yet.

And thanks for reading!


Solution

  • jQuery's .load() is async. Thus welcome.js will be executed, before the functions are defined. You have to use a callback. See https://api.jquery.com/load/