兼容性
前端兼容性与跨浏览器适配
浏览器版本监控
当你在网页中嵌入
if (browser === "the-one-they-make-you-use-at-work") {
getTheOldLameExperience();
} else {
showOffAwesomeNewFeature();
}
改为了:
if (Modernizr.awesomeNewFeature) {
showOffAwesomeNewFeature();
} else {
getTheOldLameExperience();
}
IE 版本限定
IE,特别是
- 使用一行代码来指定浏览器使用特定的文档模式。
<meta http-equiv="x-ua-compatible" content="IE=9" />
<meta http-equiv="x-ua-compatible" content="IE=8" />
<meta http-equiv="x-ua-compatible" content="IE=7" />
- 在一些情况下,我们需要限定浏览器对文档的解析到某一特定版本,或者将浏览器限定到一些旧版本的表现中。可以用如下的方式:
<meta http-equiv="x-ua-compatible" content="IE=EmulateIE9" />
<meta http-equiv="x-ua-compatible" content="IE=EmulateIE8" />
<meta http-equiv="x-ua-compatible" content="IE=EmulateIE7" />
使用这种写法,浏览器或者使用标准模式进行解析,或者使用
- 为了测试,我们也可以使用下面的语句指定浏览器按照最高的标准模式解析页面。
<meta http-equiv="x-ua-compatible" content="IE=edge" />
- 多个模式的指定。我们可以用逗号分割多个版本,这种情况下,浏览器会从这个列表中选择一个他所支持的最高版本来使用标准模式进行渲染。如下面的例子,在
IE8 进行浏览时,将会使用IE7 的标准模式进行渲染,因为他本身不支持IE9 和IE10 。
<meta http-equiv="x-ua-compatible" content="IE=7,9,10" />
Polyfill
Polyfill.io
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script
src="https://cdn.polyfill.io/v2/polyfill.min.js?callback=main"
async
defer
></script>
<script>
function main() {
var node = document.createElement("script");
node.src = "index.js";
document.body.appendChild(node);
}
</script>
</head>
<body></body>
</html>
DOM
if (!document.querySelectorAll) {
document.querySelectorAll = function (selectors) {
var style = document.createElement("style"),
elements = [],
element;
document.documentElement.firstChild.appendChild(style);
document._qsa = [];
style.styleSheet.cssText =
selectors +
"{x-qsa:expression(document._qsa && document._qsa.push(this))}";
window.scrollBy(0, 0);
style.parentNode.removeChild(style);
while (document._qsa.length) {
element = document._qsa.shift();
element.style.removeAttribute("x-qsa");
elements.push(element);
}
document._qsa = null;
return elements;
};
}
if (!document.querySelector) {
document.querySelector = function (selectors) {
var elements = document.querySelectorAll(selectors);
return elements.length ? elements[0] : null;
};
}
优雅降级与渐进增强
渐进增强是指针对低版本浏览器进行构建页面,保证最基本的功能,然后再针对高级浏览器进行效果、交互等改进和追加功能达到更好的用户体验。优雅降级则是反其道行之,一开始就构建完整的功能,然后再针对低版本浏览器进行兼容。
优雅降级和渐进增强印象中是随着
渐进增强
区别:优雅降级是从复杂的现状开始,并试图减少用户体验的供给,而渐进增强则是从一个非常基础的,能够起作用的版本开始,并不断扩充,以适应未来环境的需要。降级
在这种设计范例下,旧版的浏览器被认为仅能提供“简陋却无妨
内容是我们建立网站的诱因。有的网站展示它,有的则收集它,有的寻求,有的操作,还有的网站甚至会包含以上的种种,但相同点是它们全都涉及到内容。这使得“渐进增强”成为一种更为合理的设计范例。这也是它立即被