简体   繁体   English

当脚本开始时有几个Jquery Selectors时,如何优化页面的加载?

[英]How i can optimize the load of my page when i have severals Jquery Selectors at the start of my script?

I have several jquery selector at the beginning of my javascript. 我的javascript开头有几个jquery选择器。

jQuery('.enter').show();
jQuery('.btnsecond').show();
jQuery('#id div.my-class').hide();
jQuery('.classes p:last').hide();

this jquery code run at any reload of the page... 这个jQuery代码在页面的任何重载下运行...

I think its cause a process to select the correct DOM, which solution could be to simplify, or optimize this process of loading ? 我认为这导致选择正确DOM的过程,哪个解决方案可以简化或优化此加载过程? Maybe locate the dom diferently, using Css. 也许使用CSS不同地定位dom。

Thanks. 谢谢。

jQuery('.enter, .btnsecond').show();
jQuery('#id div.my-class, .classes p:last').hide();

Since you have no programming logic applied in these javascript/jQuery statements, the fastest way to apply those initial conditions would be to just set them with CSS rules in a stylesheet, not with javascript. 由于您没有在这些javascript / jQuery语句中应用编程逻辑,因此应用这些初始条件的最快方法是仅在样式表中使用CSS规则而不是在javascript中设置它们。 This way they will be applied immediately before the page even displays, rather than set via javascript which has to wait until the DOM is loaded before it can run. 这样,它们将在页面显示之前立即应用,而不是通过JavaScript设置,而javascript必须等待DOM加载后才能运行。

.enter, .btnsecond {display: block;}
#id div.my-class, .classes p:last {display: none;}

To add to mgraphs code you can specify the context in your selector. 要添加到mgraphs代码,您可以在选择器中指定上下文。 Meaning you specify the containing element of your items so that it only searches that container for your elements. 这意味着您可以指定项目的包含元素,以便仅在该容器中搜索您的元素。 This reduces dom traversing. 这减少了dom遍历。

$exampleContainerDiv = $("#ContainerDivForSelectorsBelowExample");
jQuery('.enter, .btnsecond', $exampleContainerDiv).show();
jQuery('#id div.my-class, .classes p:last', $exampleContainerDiv).hide();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM