How to load jQuery programatically

#javascript #jquery #stackoverflow

Written by Anders Marzi Tornblad

StackOverflow user ThomasReggi was trying to load jQuery dynamically by adding a script element from code, but couldn't use jQuery immediately. The problem with loading code like this is that you have to wait for the code to finish loading, before you can use it.

I put together a working JSFiddle with a small example, that demonstrates exactly what was expected:

There are a few issues with that method of loading javascript dynamically, though. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework.

It's possible to use some of the existing JavaScript loaders, or write your own by listening to the load event on the script element:

// Immediately-invoked function expression
(function() {
    // Load the script
    const script = document.createElement('SCRIPT');
    script.src = '';
    script.type = 'text/javascript';
    script.onload = function() {
        var $ = window.jQuery;
        // Start using jQuery through $ here...