简体   繁体   English

JavaScript性能,同时将大量子代添加到大量元素中

[英]JavaScript performance while appending a large number of children to a large number of elements

I have many select inputs on a page (96 or 384). 我在页面上有很多选择输入(96或384)。 Each has an extensive list of options - almost 1000. As a result the size of the page is between 4-8MB (1-4MB compressed). 每个选项都有一个广泛的选项列表-几乎有1000个。因此,页面大小在4-8MB之间(压缩的1-4MB)。 I decided to make to page load faster by putting list of options just once and then add it to each input with JavaScript. 我决定通过只放置选项列表一次,然后使用JavaScript将其添加到每个输入中来提高页面加载速度。

Unfortunately, the browser either needs a lots of time to finish the task (~3 minutes on FF 10) or hangs (Chrome 17). 不幸的是,浏览器要么需要大量时间才能完成任务(在FF 10上约为3分钟),要么会挂起(Chrome 17)。 I tried to accomplish the task with jQuery and pure JS. 我试图用jQuery和纯JS完成任务。 No difference at all. 完全没有区别。

Is the task feasible? 任务可行吗? What should I know to write fast and efficient JavaScript? 我应该知道如何编写快速高效的JavaScript?

屏幕截图

Edit: I put all the options to a single string and use innerHTML to put it to the select input. 编辑:我将所有选项放在单个字符串中,并使用innerHTML将其放置到选择输入中。 Thanks for such a quick response. 感谢您的快速回复。

Edit2: I generate elements the way suggested by Diodeus. Edit2:我按照Diodeus的建议生成元素。 However, I load options when the select element is in focus (thanks rlemon). 但是,当select元素处于焦点位置时(感谢rlemon),我会加载选项。 I believe all the answers are very helpful and might be valuable for anyone having similar problem. 我相信所有答案都将非常有帮助,并且对于任何有类似问题的人都可能是有价值的。 Thank you all. 谢谢你们。

Build up your HTML as a string or single object an inject it all into that page in one go. 将您的HTML构建为字符串或单个对象,然后一次性将其全部注入该页面。 DOM re-writes are slow because document re-flows must be calculated for each insert. DOM重写很慢,因为必须为每个插入计算文档重排。

Why do you need to append the children separately? 为什么需要分别追加孩子? Simply wrap the whole list with the options in another element and append that one. 只需将选项列表包装在另一个元素中,然后附加该元素即可。 This should be much faster since it will be just one operation instead of 1000. 这应该快得多,因为它将是一次操作,而不是1000次。

I would suggest you to use ajax. 我建议您使用ajax。 Replace standard input selects with 3rd party combobox Eg: Jquery UI Combobox. 用第三方组合框替换标准输入选择,例如:Jquery UI组合框。 First you load all empty comboboxes. 首先,您加载所有空的组合框。 It items will be loaded as soon as use click to open drop down list. 使用单击打开下拉列表后,将立即加载该项目。

You can do it quite easy with jquery and jquery UI. 您可以使用jquery和jquery UI相当容易地做到这一点。

It's faster to have everything loaded by default on the HTML than using JS to append thousands of elements. 在HTML上默认加载所有内容比使用JS附加数千个元素要快。

Your server gives you a guarantee of quality/speed the user's computer won't. 您的服务器为您提供了用户计算机无法提供的质量/速度的保证。

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

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