I have read in several places how to fallback on a local copy of the jQuery library should the link hosted by either google or microsoft or other fail.

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
document.write(unescape("%3Cscript src='/Scripts/jquery-1.3.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

My application works within an intranet environment however and occasionally the external jQuery link doesn't so much fail but takes a long time to load (due to external internet connection issues).

I'm wondering if there is a way to not only use such a fallback but set a timeout for the CDN link so that if the link takes a certain amount of time it should fail and call on the fallback.

Something like:

if(timetoloadjquery > n) {
    Use fallback local jQuery library.
}

Perhaps some kind of loop that checks if the jQuery is defined and if after so many iterations it is not....do something else?

Thanks for the help.

有帮助吗?

解决方案

This may help you. After 5-seconds have passed, Javascript checks if jQuery is available, if not, then loads the library from local server.

1. With a timer

<script>
setTimeout(function() {
  if(window.jQuery) return;
  var n = document.getElementsByTagName("script")[0];
  n.parentNode.insertBefore(document.createElement("script"), n).src = "assets/jQuery/jquery-1.7.2.min.js";
}, 5000);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

2. This one doesn't have a timer, it loads a local version if the CDN version fails.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
<script type="text/javascript">window.jQuery || document.write("<script type='text/javascript' src='js/jquery-1.8.3.min.js'>\x3C/script>")</script>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top