user1852176
user1852176

Reputation: 455

Wait for jQuery to load

I'm trying to check if jQuery is loaded. If not, load it, then proceed to load external javascript files. The issue I'm having is one of the external files expects to have jQuery already loaded, so I get a 'jQuery not defined" error. Is there a way I can load jQuery using JavaScript, and as soon as it's done then continue?

if(!window.jQuery){
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
}

//load these scripts after jquery has been loaded

<script src="/some/other/js/file/that/requires/jquery"></script>
<script src="/some/other/js/file/that/requires/jquery"></script>

What I'd like to do is wait for this to completely load before continuing. I tried this but I got errors about exceeding call stack

Upvotes: 0

Views: 2624

Answers (1)

Blazemonger
Blazemonger

Reputation: 92983

Consider the technique tried and tested by HTML5Boilerplate instead:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>

Note that <script src="//ajax.googleapis.com only works on an actual http: or https: server; if you're testing on a local filesystem, write <script src="http://ajax.googleapis.com instead.

Upvotes: 5

Related Questions