5

I am loading the following javascript files from a CDN. Is there any way I can check if these have been loaded correctly and if not, load them from a local folder?

http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.min.js http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js

I know I can check the jquery file but not sure about the others. Any tips?

2 Answers 2

11

In your HTML, you can do something like this:

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script>!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>

The example shown is loading jquery from Google CDN and falls back on a local copy of JQuery if that fails.

Credits to HTML5 Boilerplate for showing the trick

6
  • For ui and validate, do that same, checking for $.ui or $.validate
    – scottm
    Oct 27, 2010 at 18:03
  • Thanks to both. Scottm - $.ui does the trick in checking if ui javascript is loaded but unfortunately $.validate does not. Any tips as how I check for the validate plugin?
    – amateur
    Oct 27, 2010 at 20:36
  • Anyone have any idea regarding checking if the validate plugin is loaded?
    – amateur
    Oct 28, 2010 at 23:36
  • 1
    I think you can check for existence of jQuery.fn.myPlugin & if it hasn't loaded from the external source, then fetch it from the local copy. So for your case it could be something like : <script>!window.jQuery.fn.validate && document.write('<script src="js/jquery.validate.min.js"><\/script>')</script>
    – Rajat
    Oct 28, 2010 at 23:56
  • Is there a quick an easy way to integrate into this https - so that the cdn will change its url to https if the web page is in https?
    – amateur
    Nov 3, 2010 at 21:27
3

YepNope.js is a more robust solution for loading resources (like js files), checking whether they've been loaded or not, and then providing a fallback if necessary. This is just 1 feature among many provided by the library.

1
  • This resource link is broken... Can you please, update it? Jul 25, 2020 at 4:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.