Search code examples
javascriptjquerytypescriptpapaparse

Cannot use javascript function after script loaded using jQuery


I'm trying to programmatically load a local javascript file - papaparse library, and then use one of its functions:

$.getScript("./Content/Scripts/papaparse.js", function () {
    console.log("Papaparse loaded successfully");
    Papa.parse(file, { skipEmptyLines: true, header: false, complete: completeCallback });
});

The script loaded successfully, but calling the parse method throws an error:

ReferenceError: Papa is not defined

Within papaparse library, Papa defined as follows:

(function (global) {
    "use strict";

    var Papa = {};
    Papa.parse = someFunction;
    .
    .
    global.Papa = Papa;
}

If that helps, this entire code is called from a typescript file.
What am I doing wrong?


Solution

  • As Castro pointed out in his answer here that according to offical documentation of Jquery's getScript

    The callback of getScript method is fired once the script has been loaded but not necessarily executed.

    That means when getScript's callback function is called then the target script is only being loaded in current page context not fully executed so you need to give some time to JavaScript engine to execute that script. How could you give that time. Hmm one of the options is setTimeout/setInterval.

    You could use setTimeout/setInterval right inside callback function of getScript.

    Modified version of your code would look like :-

    $.getScript("./Content/Scripts/papaparse.js", function () {
        console.log("Papaparse loaded successfully");
        function dealWithPapa() {
           Papa.parse(file, { skipEmptyLines: true, header: false, complete: completeCallback });
        }
        //regularly check after 100ms whether Papa is loaded or not
        var interval = setInterval(function() {
            if(Papa !== undefined) {
                //once we have reference to Papa clear this interval
                clearInterval(interval);
                dealWithPapa();
            }       
        },100);
    
    });
    

    I hope that would clear your doubt.