jok*_*yme 10 javascript jquery cross-browser requirejs
jQuery 2. 0日益成熟:http://blog.jquery.com/2013/03/01/jquery-2-0-beta-2-released/
jQuery 2.0打破了与旧浏览器的兼容性,因此必须知道何时使用jQuery 1.9.建议的方法是使用IE的条件注释:
<!--[if lt IE 9]>
<script src="jquery-1.9.1.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="jquery-2.0.0b2.js"></script>
<!--<![endif]-->
Run Code Online (Sandbox Code Playgroud)
当前的Web开发最佳实践表明我们应该避免浏览器嗅探或用户代理字符串解析,但这不是条件注释的那种吗?
jQuery 2.0是否只会破坏与旧版Internet Explorer的兼容性?或者是否有其他浏览器在2.0中更糟糕?
如果这不仅影响Internet Explorer(这是条件评论唯一有效的地方),那么我们应该采用什么策略来选择最好的jQuery?
在JavaScript环境中是否存在可全局访问的值/对象/函数/等,其存在可用于表示与jQuery 2.0的兼容性(例如,功能检测)?
我的项目目前使用Require.JS来模块化我的代码.我的代码目前只在遇到需要它的第一部分时加载jQuery.
使用Require.JS加载正确版本的jQuery的最佳方法是什么?
我正在考虑:
在加载Require.JS之前使用IE条件注释,然后手动"定义"jQuery
在设置Require.JS路径的代码中使用JS功能检测(在任何需要jQuery之前)根据需要将路径设置为1.9或2.0(我的首选方法)
总是使用1.9,无论什么(最安全,最无聊的方法)
ddo*_*nko 13
适应niaccurshi对AMD规范的回答.
// 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 */ })
Run Code Online (Sandbox Code Playgroud)
实际上有一个更优雅的解决方案,它被用于BBC他们的响应式新闻网站.
它本质上检测被认为是的浏览器new,因此与之兼容jQuery 2.0+,因此将其他所有东西都留作old浏览器.你也许可以复制这个Require.js,但现实是你不需要......
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;
}
Run Code Online (Sandbox Code Playgroud)
来源: 链接
你应该为每个脚本添加一个回调函数jQuery,调用jQueryRunning参数等于它的版本号,这可以帮助你决定进一步的函数来运行,并且有一个好处,让你知道什么时候jQuery代码已被嵌入(just in case the connection is slow and it takes a while to download).
如果使用Require.js它可能不是你想要关注的东西!
我说这是一个优雅的解决方案,因为你是对的,问题不仅是旧版本IE,它还是旧版本Firefox (before 3.5)和旧版移动浏览器(如果他们甚至处理javascript!)