赞
踩
- <body>
- <div class="box" style="position: relative; top: 200px"></div>
- </body>
-
- <script>
- const box = document.querySelector(".box");
- console.time();
- console.log(box.offsetTop); // default: 0.3291015625 ms
- console.timeEnd();
-
- console.log("=================");
-
- console.time();
- console.log(box.computedStyleMap().get("top").value); // default: 0.051025390625 ms
- console.timeEnd();
-
- console.log("=================");
-
- console.time();
- console.log(box.getBoundingClientRect().y); // default: 0.049072265625 ms
- console.timeEnd();
-
- console.log("=================");
-
- console.time();
- console.log(box.style.top); // default: 0.029052734375 ms
- console.timeEnd();
- </script>
结论:如果我们想获取距离父元素顶端的距离的时候,应该尽量采用后三种
- <body>
- <div class="box"></div>
- </body>
-
- <script>
- console.time();
- document.querySelector(".box"); // default: 0.078857421875 ms
- console.timeEnd();
-
- console.log("=================");
-
- console.time();
- document.getElementsByClassName("box"); // 0.01806640625 ms
- console.timeEnd();
- </script>
结论:如果在一个同步代码块需要很多元素查询时,请尽可能换成第二种
- const img = document.createElement("img");
- img.src = "./png.png";
- console.time();
- img.onload = function () {
- console.timeEnd(); // default: 5.255126953125 ms
-
- console.log("=================");
-
- const img2 = document.createElement("img");
- img2.src = "./svg.svg";
- console.time();
- img2.onload = function () {
- console.timeEnd(); // default: 9.476806640625 ms
- };
- };
结论:同样大小的 png 和 svg,svg 要比 png 图片加载的慢一些
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。