Victor Ferreira Victor Ferreira - 1 month ago 10
Javascript Question

Programatically loads Javascript file and load code when it's finished

I'm working in a React project that uses jQuery and I need to import a jQuery library to it.

Basically, what I need right now is a way to load a javascript in my project dynamically and when it finishes loading I need to run a javascript code.

something like this:

$(function(){
loadJavascript('myscript.js',function(){
//run this code when myscript has finished loading
});
});

Answer

$.getScript does what you want.

$(function() {
    $.getScript('myscript.js', function() {
        // run when myscript has finished loading
    });
});