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?

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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: 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?
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!
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?
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 :)

1 Comment

Does this work? Don't you need http: in the first script src?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.