load jQuery from source
What I like to do is to drop my local jquery.js and have it hosted somewhere else. But what if Google is down? So let's code a fallback that uses another source if jQuery is "still" not loaded...
I made this test case but it does not seem to work, maybe someone can help me out:
http://jsfiddle.net/RBz4n
Is it possible to load a single page from an external website? Yes, it's possible, but you'll need 1 line of PHP :) If you only need RSS feeds and you don't mind relying on Google you could use jquery-feeds.
First, you need to make sure that jQuery is included before any scripts that use it. This can be tricky if you have javascript embedded in partials. If you load jQuery in the header and all of your other script in a script block at the end of the body, you can be sure that jQuery is loaded before your other code.
You can use jQuery to support both synchronous and asynchronous code, with the `$.
The load() method was deprecated in jQuery version 1.8 and removed in version 3.0. Use the on() or trigger() method instead. Use .
This works fairly well (from HTML5 Boilerplate):
<!-- Grab Google CDN's jQuery. fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>
Here is a pure javascript solution that starts out by detecting if jQuery is available. If not, it tries the CDN version. If that's not available, it tries the local version. Handles 404 errors. I use this in a solution that doesn't know whether the website has included jQuery.
<script>
if (typeof jQuery === "undefined") {
loadjQuery("//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js", verifyJQueryCdnLoaded);
} else
main();
function verifyJQueryCdnLoaded() {
if (typeof jQuery === "undefined")
loadjQuery("script/jquery-1.6.1.js", main);
else
main();
}
function loadjQuery(url, callback) {
var script_tag = document.createElement('script');
script_tag.setAttribute("src", url)
script_tag.onload = callback; // Run callback once jQuery has loaded
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') callback();
}
script_tag.onerror = function() {
loadjQuery("script/jquery-1.6.1.js", main);
}
document.getElementsByTagName("head")[0].appendChild(script_tag);
}
function main() {
if (typeof jQuery === "undefined")
alert("jQuery not loaded.");
$(document).ready(function () {
// Rest of your code here...
});
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With