gpt4 book ai didi

jQuery (文档).ready(函数($)

转载 作者:行者123 更新时间:2023-12-01 08:19:59 26 4
gpt4 key购买 nike

我编写了一个 jQuery 脚本(如下),并使用了 (document).ready(function($)) 函数它会减慢网站速度吗?如果是的话,您能告诉我一种在不减慢网站速度的情况下创建此类功能的方法吗?非常感谢!

<script>
jQuery(document).ready(function($){
$('#columns').wrapInner('<div id="columnsInner" />');
$("div.productInfo:first").wrap("<div id='productDetails' />");
});
</script>

最佳答案

仅使用ready不会对性能产生重大影响。一个更大的问题是您使用哪些选择器。 例如,“div.productInfo:first”在带有 querySelector 的现代浏览器上应该没问题。 . 但是,在较旧的浏览器上,它可能必须循环遍历 div 直到找到匹配项。如果该 div 有一个 id,则可以避免这种情况。我不一定提倡这样做;这只是一般性考虑。

编辑:实际上,我相信 jQuery 不会利用 querySelector(All),因为它指出:

Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first")."

因此,即使对于较新的浏览器,最好使用:

$("div.productInfo").filter(":first")

在旧版浏览器中,jQuery 仍然需要循环遍历 div。

关于jQuery (文档).ready(函数($),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7909354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com