Jonhas
Jonhas

Reputation: 125

Loading jQuery if not loaded - failed approach

This is what I have in :

<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">testfunction("hello");</script>

Inside myscript.js:

if(!window.jQuery)
{
  var script = document.createElement('script');
  script.type = "text/javascript";
  script.src = 'jquery-1.9.0.min.js';
  document.getElementsByTagName('head')[0].appendChild(script);
}

function testfunction(str) {
    $(document).ready(function () {
      alert(str);
    });
}

Of course jQuery is not needed for the current testfunction, but it will be needed. Using this approach, jQuery is downloaded but NOT loaded to the browser when calling to testfunction() (Uncaught ReferenceError: $ is not defined).

What I could do is to load jQuery in a different script before my JS is loaded. In that case, it will work, but I would have three different scripts and that seems to be not elegant in my honest opinion.

Is there any other way to achieve this?

Thanks!

Upvotes: 1

Views: 2447

Answers (2)

Christophe
Christophe

Reputation: 28124

With your code, the script will be loaded asynchronously. You need to add to the script tag an onload event that will trigger the parts that are dependent on jQuery.

If you want the script to be loaded in a synchronous way, use document.write:

window.jQuery||document.write(unescape("%3Cscript src='"+jQueryURL+"' type='text/javascript'%3E%3C/script%3E"));

The document.write technique is very common, just keep in mind that you cannot use it after your document has loaded (or else it will overwrite the whole page).

If you want to use dynamic loading on a larger scale, look at existing loader or AMD libraries.

Upvotes: 0

RenegadeMatrix
RenegadeMatrix

Reputation: 141

You might want to try looking at this answer. It may not be waiting until jQuery is fully loaded.

Upvotes: 3

Related Questions