Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load JS inside JS [duplicate]

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

like image 510
Riju Mahna Avatar asked Jan 25 '13 11:01

Riju Mahna


People also ask

Is it possible to dynamically load external JavaScript files in JavaScript?

Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.

How do you include js file inside js file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.

How do I load JavaScript libraries?

Locate the correct Javascript download of the library you want to install. Download the library and make a copy in your sketch folder. (If you're using the web editor, you can upload the relevant files using Upload file in the dropdown in the “Sketch Files” sidebar.) Add a <script> tag to your sketch's index.


2 Answers

My guess is that in your DOM-only solution you did something like:

var script = document.createElement('script');
script.src = something;
//do stuff with the script

First of all, that won't work because the script is not added to the document tree, so it won't be loaded. Furthermore, even when you do, execution of javascript continues while the other script is loading, so its content will not be available to you until that script is fully loaded.

You can listen to the script's load event, and do things with the results as you would. So:

var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes
like image 86
Zirak Avatar answered Oct 07 '22 12:10

Zirak


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
});
like image 173
kayen Avatar answered Oct 07 '22 13:10

kayen