Offir Pe'er Offir Pe'er - 4 months ago 16
jQuery Question

Cannot load Script using Ajax request

I need to execute a function after a certain script was loaded so I load the script using an ajax call and on the success I invoke the function that uses an object that was suppose to be loaded already from that script and I get an error that this object is undefined.
Here is my code:

function LoadInlineManualScript() {
return $.ajax({
url: "../Scripts/inline-manual-player.js",
dataType: "script",
beforeSend: function () {
loader.hide();
loader.unbind();
},
success: SetInlineManualCallbacks
});
}


function SetInlineManualCallbacks() {
debugger;
//Here I get the error!
window.inline_manual_player.setCallbacks({
onTopicDone: function (player, topic_id, step_id) {
console.log('Step was displayed.');
}
});
}


And I get
Uncaught TypeError: Cannot read property 'setCallbacks' of undefined
.

I tried to change the call to use
async:false
but it didn't help.

Answer

This answer is a combination of some answers I got here:

The function I use to load the script instead of using Jquery's $.getScript is:

   //Must load the script after inlineManualTracking object is ready.
    function LoadInlineManualScript() {
        loader.hide();
        loader.unbind();
        var script = document.createElement('script');
        script.src = "../Scripts/inline-manual-player.js";
        // your callback will fire when the script is loaded and executed
        script.onload = WaitForInlineManualScriptToLoad;
        // it will start to load right after appended, and execute of course
        document.body.appendChild(script);
    }

The script I load has "use strict" and it cannot be loaded with jquery because of the following reason: "use strict"; + jQuery.getScript() = script can't export to global namespace like epascarello mentioned earlier.

Even after using Leo's answer I still had a problem with that object and that's why I use the following function after the onload event of the script.

function WaitForInlineManualScriptToLoad() {
    if (typeof window.inline_manual_player == 'undefined') {
        setTimeout(WaitForInlineManualScriptToLoad, 100);
        return;
    }
    InitInlineManualPlayerCallBacks();
}

function InitInlineManualPlayerCallBacks() {
    window.inline_manual_player.setCallbacks({
        onTopicDone: function (player, topic_id, step_id) {
            console.log('Step was displayed.');
        }
    });
}

This works! it's not the prettiest, but it works.
The developer of inline-manual tool had responded here(Marek) and mentioned the fact that my site in under "Test" mode. There was no way we could know this can affect.

Comments