Reputation: 806
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?
Upvotes: 3
Views: 12501
Reputation: 1036
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
Upvotes: 2
Reputation: 154818
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);
Upvotes: 4
Reputation: 13134
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 :)
Upvotes: 2