Search code examples
javascriptjquery

Dynamically load JS inside JS


I have a dynamic web page where I need to import an external JS file (under an IF condition) inside another javascript file.

I tried to search for a feasible solution but it didn't work.

I have tried loading a JS file to the DOM using document.createElement() but it also didn't work. Apparently the Js was loaded into the DOM but was not accessible in the current JS file.

Solution in jQuery will also be fine


Solution

  • jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

    jQuery.loadScript = function (url, callback) {
        jQuery.ajax({
            url: url,
            dataType: 'script',
            success: callback,
            async: true
        });
    }
    

    and use it like:

    if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
        //Stuff to do after someScript has loaded
    });