Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

前端 未结 23 1450
太阳男子
太阳男子 2020-11-21 07:19

What would be a good way to attempt to load the hosted jQuery at Google (or other Google hosted libs), but load my copy of jQuery if the Google attempt fails?

I\'m n

相关标签:
23条回答
  • 2020-11-21 07:42

    Google Hosted jQuery

    • If you care about older browsers, primarily versions of IE prior to IE9, this is the most widely compatible jQuery version
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    • If you don’t care about oldIE, this one is smaller and faster:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

    Backup/Fallback Plan!

    • Either way, you should use a fallback to local just in case the Google CDN fails (unlikely) or is blocked in a location that your users access your site from (slightly more likely), like Iran or sometimes China.
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>if (!window.jQuery) { document.write('<script src="/path/to/your/jquery"><\/script>'); }
    </script>
    

    Reference: http://websitespeedoptimizations.com/ContentDeliveryNetworkPost.aspx

    0 讨论(0)
  • 2020-11-21 07:42
    if (typeof jQuery == 'undefined')) { ...
    

    Or

    if(!window.jQuery){
    

    Will not works if cdn version not loaded, because browser will run through this condition and during it still downloading the rest of javascripts which needs jQuery and it returns error. Solution was to load scripts through that condition.

        <script src="http://WRONGPATH.code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script><!--  WRONGPATH for test-->
      <script type="text/javascript">
      function loadCDN_or_local(){
        if(!window.jQuery){//jQuery not loaded, take a local copy of jQuery and then my scripts
          var scripts=['local_copy_jquery.js','my_javascripts.js'];
          for(var i=0;i<scripts.length;i++){
          scri=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
          scri.type='text/javascript';
          scri.src=scripts[i];
        }
      }
      else{// jQuery loaded can load my scripts
        var s=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
        s.type='text/javascript';
        s.src='my_javascripts.js';
      }
      }
      window.onload=function(){loadCDN_or_local();};
      </script>
    
    0 讨论(0)
  • 2020-11-21 07:43

    Although writing document.write("<script></script>") seems easier for jQuery backoff, Chrome gives validation error on that case. So I prefer breaking "script" word. So it becomes safer like above.

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
    <script>if (typeof jQuery === "undefined") {
       window.jqFallback = true;
       document.write("<scr"+"ipt src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js'></scr"+"ipt>");
    } </script>
    

    For long term issues, it would be better to log JQuery fallbacks. In the code above, if first CDN is not available JQuery is loaded from another CDN. But you could want to know that erroneous CDN and remove it permanently. (this case is very exceptional case) Also it is better to log fallback issues. So you can send erroneous cases with AJAX. Because of JQuery isn't defined, you should use vanilla javascript for AJAX request.

    <script type="text/javascript">
        if (typeof jQuery === 'undefined' || window.jqFallback == true) {
            // XMLHttpRequest for IE7+, Firefox, Chrome, Opera, Safari
            // ActiveXObject for IE6, IE5
            var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            var url = window.jqFallback == true ? "/yourUrl/" : "/yourUrl2/";
            xmlhttp.open("POST", url, true);
            xmlhttp.send();
        }
    </script>
    
    0 讨论(0)
  • 2020-11-21 07:44

    You might want to use your local file as a last resort.

    Seems as of now jQuery's own CDN does not support https. If it did you then might want to load from there first.

    So here's the sequence: Google CDN => Microsoft CDN => Your local copy.

    <!-- load jQuery from Google's CDN -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <!-- fallback to Microsoft's Ajax CDN -->
    <script> window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js">\x3C/script>')</script> 
    <!-- fallback to local file -->
    <script> window.jQuery || document.write('<script src="Assets/jquery-1.8.3.min.js">\x3C/script>')</script> 
    
    0 讨论(0)
  • 2020-11-21 07:45

    There are some great solutions here, but I'll like to take it one step further regarding the local file.

    In a scenario when Google does fail, it should load a local source but maybe a physical file on the server isn't necessarily the best option. I bring this up because I'm currently implementing the same solution, only I want to fall back to a local file that gets generated by a data source.

    My reasons for this is that I want to have some piece of mind when it comes to keeping track of what I load from Google vs. what I have on the local server. If I want to change versions, I'll want to keep my local copy synced with what I'm trying to load from Google. In an environment where there are many developers, I think the best approach would be to automate this process so that all one would have to do is change a version number in a configuration file.

    Here's my proposed solution that should work in theory:

    • In an application configuration file, I'll store 3 things: absolute URL for the library, the URL for the JavaScript API, and the version number
    • Write a class which gets the file contents of the library itself (gets the URL from app config), stores it in my datasource with the name and version number
    • Write a handler which pulls my local file out of the db and caches the file until the version number changes.
    • If it does change (in my app config), my class will pull the file contents based on the version number, save it as a new record in my datasource, then the handler will kick in and serve up the new version.

    In theory, if my code is written properly, all I would need to do is change the version number in my app config then viola! You have a fallback solution which is automated, and you don't have to maintain physical files on your server.

    What does everyone think? Maybe this is overkill, but it could be an elegant method of maintaining your AJAX libraries.

    Acorn

    0 讨论(0)
  • 2020-11-21 07:46
    if (typeof jQuery == 'undefined') {
    // or if ( ! window.jQuery)
    // or if ( ! 'jQuery' in window)
    // or if ( ! window.hasOwnProperty('jQuery'))    
    
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = '/libs/jquery.js';
    
      var scriptHook = document.getElementsByTagName('script')[0];
      scriptHook.parentNode.insertBefore(script, scriptHook);
    
    }
    

    After you attempt to include Google's copy from the CDN.

    In HTML5, you don't need to set the type attribute.

    You can also use...

    window.jQuery || document.write('<script src="/libs/jquery.js"><\/script>');
    
    0 讨论(0)
提交回复
热议问题