1

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!

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
Jonhas
  • 125
  • 1
  • 1
  • 9
  • 2
    Just add the script tag with jQuery first, then the scripts that depends on jQuery, and it should work out of the box without any trickery ? – adeneo Mar 05 '13 at 17:21
  • Just add the script the "normal" way. It's much more elegant than any attempt at loading it dynamically. – JJJ Mar 05 '13 at 17:22
  • 1
    I don't want to load jQuery twice for the user (this is a JS embedded into another webpage, which is out of control for me, and that's why I'm checking if the webpage has forced the user to load jQuery already). – Jonhas Mar 05 '13 at 17:24

2 Answers2

3

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

Community
  • 1
  • 1
0

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.

Christophe
  • 27,383
  • 28
  • 97
  • 140