3

I am trying to include jQuery to an HTML page conditionally. It only needs to be added if it doesn't exist yet.

I am using the following code near the top of my body tag to inject a script tag that includes the jQuery library in the head.

<script type="text/javascript">

    if (typeof jQuery === 'undefined') {
        alert('now adding jquery');
        var head = document.getElementsByTagName("head")[0];
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';
        head.appendChild(script);
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
    } else {
        alert('jquery already present');
    }
</script>

When I execute it, I get the message that jQuery is still not present after adding it. The script tag does correctly show up in the loaded page's source.

Trying to make use of jQuery a little further down below in my page, confirms that jQuery is indeed not working. As expected, Chrome's JavaScript console says '$ not defined'.

How can I get this to work?

Jay
  • 740
  • 4
  • 8
  • 19

3 Answers3

4

A script loads asynchronously. This means its contents are not directly available after appending the element.

Use onload instead:

script = document.createElement('script');

script.onload = function() {
    // jQuery is available now
};

script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';

head.appendChild(script);
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • Thanks, that did the trick. The only problem is that jQuery is sometimes available incredibly late. Sometimes a second or two after the page has loaded. I need it available faster than that. Can I somehow guarantee that jQuery will be dynamically added to the page in time for the $(document).ready event? – Jay Oct 28 '11 at 12:09
  • @Jay: This should not be slower/faster than a normal script tag. Google's CDN is rather fast, so I don't know how it can take 2 seconds. Where are you executing the appending code? – pimvdb Oct 28 '11 at 16:00
  • It was probably so slow because I had included a couple of alert() calls. When I removed those, it was faster right away. But I was still having trouble correctly initializing all my jQuery events after successfully firing off the script.onLoad event. That's why I'm now including jQuery with a document.write call (split script tags). It's too bad that IE can't handle this if it's coming from an external js file. Chrome can handle it just fine. Oh well! – Jay Oct 28 '11 at 17:59
  • I'm trying to add jquery and bootstrap, but getting .. Uncaught Error: Bootstrap's JavaScript requires jQuery. I tried to set script.async = false; but not working too. How to do it correctyl? – aldrien.h Apr 22 '20 at 05:00
2

Boilerplate uses this method to test if jQuery is loaded by google, if not use local:

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

Seems like what you want to achieve :)

Marco Johannesen
  • 13,084
  • 6
  • 31
  • 36
2

You are not waiting for the script to load after appending it to document

Try this code before appending:

   function helper(){
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
   };

   script.onreadystatechange= function () {
      if (this.readyState == 'complete') helper();
   }
   script.onload= helper;

I've found it here if you want to know more

Also there are loaders like StealJS or YepNope

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Bizniztime
  • 1,016
  • 10
  • 22