0

I have a script that dynamically loads jQuery, by inserting it in <head> element:

 // pseudo code

 headElelement.insertBefore(script, firstChild);

However, immediately after that call, I start to use jQuery, but at that moment it is undefined. How is that possible ?

Zed
  • 5,683
  • 11
  • 49
  • 81
  • if the code your running after you insert jquery after inside a `$(function () {});` block? – atmd Mar 02 '15 at 08:46
  • I just run this kind of code while (typeof jQuery === 'undefined') { } which runs forever – Zed Mar 02 '15 at 08:50
  • Please post the relevant code, otherwise it's just guesswork: what do you mean with the pseudo code, do you really load jquery in the HTML itself like `...`? Where do you try to use it, you say " immediately after that call", so in the head? – Ariel Mar 02 '15 at 08:55

2 Answers2

0

That's because jQuery is not fully loaded yet. You may need to execute your jQuery code only after jQuery has been loaded by attaching an event handler to the onload event of your dynamically created script element as shown below.

script.onload = function() {
    // Put your jQuery code here.
    console.log(jQuery);
};

Cross-Browser solution for supporting older browsers like IE8 and below:

script.onload = script.onreadystatechange = function(event) {
    event = event || window.event;
    if (event.type === "load" || (/loaded|complete/.test(script.readyState))) {
        script.onload = script.onreadystatechange = null;
        // Put your jQuery code here.
        console.log(jQuery);
    }
};
icaru12
  • 1,522
  • 16
  • 21
-1

If you would post your relevant code it would be easier ;-) but anyways, this is one possible way of doing it:

<html>
<head>
  <script type="text/javascript" src="path_to_js/jquery.js"></script>
  <script type="text/javascript" src="path_to_js/your_js_code.js"></script>
  ...
</head>...

and in the file your_js_code.js you'll have:

... /* All your modules and functions here */

/* DOM loading ready */
$(document).ready(function () {
  call_your_methods_here();
});

By the way, it is usually better to load your JS files at the very end of the <body> in the HTML, that way your HTML starts displaying first and the user "sees" your page faster, while the JS code is still loading.

Ariel
  • 202
  • 1
  • 8