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

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

    Yet another fallback that replaces ajax.googleapis.com with cdnjs.cloudflare.com:

    (function (doc, $)
    {
        'use strict';
    
        if (typeof $ === 'undefined')
        {
            var script = doc.querySelector('script[src*="jquery.min.js"]'),
                src = script.src.replace('ajax.googleapis.com', 'cdnjs.cloudflare.com');
    
            script.parentNode.removeChild(script);
            doc.write('');
        }
    })(document, window.jQuery || window.Zepto);
    
    • You can stick to a jQuery version by specifying it in the string
    • Perfect for Asset Management that doesn't work with HTML snips
    • Tested in the wild - works perfect for users from China

提交回复
热议问题