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

前端 未结 23 1456
太阳男子
太阳男子 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:50

    You can use code like:

    
    
    

    But also there are libraries you can use to setup several possible fallbacks for your scripts and optimize the loading process:

    • basket.js
    • RequireJS
    • yepnope

    Examples:

    basket.js I think the best variant for now. Will cach your script in the localStorage, that will speed up next loadings. The simplest call:

    basket.require({ url: '/path/to/jquery.js' });
    

    This will return a promise and you can do next call on error, or load dependencies on success:

    basket
        .require({ url: '/path/to/jquery.js' })
        .then(function () {
            // Success
        }, function (error) {
            // There was an error fetching the script
            // Try to load jquery from the next cdn
        });
    

    RequireJS

    requirejs.config({
        enforceDefine: true,
        paths: {
            jquery: [
                '//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min',
                //If the CDN location fails, load from this location
                'js/jquery-2.0.0.min'
            ]
        }
    });
    
    //Later
    require(['jquery'], function ($) {
    });
    

    yepnope

    yepnope([{
      load: 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js',
      complete: function () {
        if (!window.jQuery) {
          yepnope('js/jquery-2.0.0.min.js');
        }
      }
    }]);
    

提交回复
热议问题