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

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

    If you have modernizr.js embedded on your site, you can use the built-in yepnope.js to load your scripts asynchronously - among others jQuery (with fallback).

    Modernizr.load([{
        load : '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'
    },{
        test : window.jQuery,
        nope : 'path/to/local/jquery-1.7.2.min.js',
        both : ['myscript.js', 'another-script.js'],
        complete : function () {
            MyApp.init();
        }
    }]);
    

    This loads jQuery from the Google-cdn. Afterwards it's checked, if jQuery was loaded successfully. If not ("nope"), the local version is loaded. Also your personal scripts are loaded - the "both" indicates, that the load-process is iniated independently from the result of the test.

    When all load-processes are complete, a function is executed, in the case 'MyApp.init'.

    I personally prefer this way of asynchronous script loading. And as I rely on the feature-tests provided by modernizr when building a site, I have it embedded on the site anyway. So there's actually no overhead.

提交回复
热议问题