当在Safari 6.0.8中加载以下给定的HTML代码时,滚动功能在~1500 ms内执行。在Chrome中,该数字为~50 ms,在FireFox中为5 ms。 我已经确定滚动方法是罪魁祸首,但我无法弄清楚为什么Safari执行它们的速度太慢。它是Safari的实现细节,还是我做错了什么?
<html>
<head>
<style>
.container {
width: 20%;
height: 100px;
background: #FF9800;
position: relative;
}
</style>
</head>
<body>
<div id="top">
<!-- 500 of these will be generated and added to the #top element -->
<div class="container">
<div style="position: absolute; left: -1px; top: -1px; right: 0px; bottom: 0px; overflow: scroll; z-index: -1; visibility: hidden;">
<div style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: scroll; z-index: -1; visibility: hidden;">
<div style="position: absolute; left: 0px; top: 0px; width: 294.796875px; height: 110px;"></div>
</div>
<div style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: scroll; z-index: -1; visibility: hidden;">
<div style="position: absolute; left: 0px; top: 0px; width: 200%; height: 200%;"></div>
</div>
</div>
</div>
</div>
<script>
//Generates the 500 container elements.
var numElements = 499;
var containerOriginal = document.querySelector(".container");
for(var i = 0; i < numElements; i++) {
var container = containerOriginal.cloneNode(true);
document.getElementById("top").appendChild(container);
}
//Why is this function so slow in Safari?
function scroll(el, et, sl, st) {
var containers = document.querySelectorAll(".container");
for(var i = 0; i < containers.length; i++) {
var container = containers[i];
var expand = container.children[0].children[0];
var shrink = container.children[0].children[1];
expand.scrollLeft = el;
expand.scrollTop = et;
shrink.scrollLeft = sl;
shrink.scrollTop = st;
}
}
//Execute the actual test on document ready.
document.addEventListener('DOMContentLoaded', function () {
console.time("test");
scroll(9, 9, 144, 101);
console.timeEnd("test");
}, false);
</script>
</body>
</html>
答案 0 :(得分:0)
我最好猜测为什么这么慢是因为你试图加载很多元素。我会建议而不是
var expand = container.children[0].children[0];
var shrink = container.children[0].children[1];
在这些你希望得到的子元素上加上一个类,并以这种方式获得它们。