picking jQuery 1.9 or 2.0 using JavaScript and Require.JS

江枫思渺然 提交于 2019-12-02 19:38:56

Adaptation of niaccurshi's answer to AMD spec.

// Do this before your first use of jQuery.

var pathToJQuery
if('querySelector' in document
    && 'localStorage' in window
    && 'addEventListener' in window) {
    pathToJQuery = '//cdn/jQuery2.0'
} else {
    pathToJQuery = '//cdn/jQuery1.9'
}

require.configure({'paths':{
    'jquery': pathToJQuery
}})

require(['jquery'], function($){ /* you get the one you need here */ })
niaccurshi

There is actually a more elegant solution, it's being used by the BBC for their responsive news website.

It essentially detects browsers considered to be new, and thus would be compatible with jQuery 2.0+, and therefore leaves everything else as an old browser. You may be able to replicate this with Require.js, but the reality is you don't need to...

if(querySelector in document
    && localStorage in window
    && addEventListener in window) {
    //Add jQuery 2.0+
} else {
    //Add jQuery 1.9.0+
}

//This is intended to be a flag that can be checked against to see if the jQuery library has been loaded into the browser.
var jQueryVersion = 0;
function jQueryRunning(ver) {
    //This could be "true", or could be a version number, it's largely down to your own system needs!
    jQueryVersion = ver;
}

Source: link

You should add a callback function to each of the scripts for jQuery, that calls jQueryRunning with the parameter equal to it's version number, this may help you decide on further functions to run down the line, and has the benefit of letting you know when the jQuery code has been embedded (just in case the connection is slow and it takes a while to download).

If using Require.js this may not be something you want to be concerned about!

I say this is a elegant solution because you're quite right, the issue isn't only old versions of IE, it's also older versions of Firefox (before 3.5) and old mobile browsers (if they even deal with javascript!)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!