JavaScript性能,同时将大量子代添加到大量元素中 [英] JavaScript performance while appending a large number of children to a large number of elements

查看:103
本文介绍了JavaScript性能,同时将大量子代添加到大量元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有很多选择输入(96或384).每个选项都有一个广泛的选项列表-差不多有1000个.因此,页面大小在4-8MB之间(压缩的1-4MB).我决定通过只放置选项列表一次,然后使用JavaScript将其添加到每个输入中来提高页面加载速度.

I have many select inputs on a page (96 or 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). I decided to make to page load faster by putting list of options just once and then add it to each input with JavaScript.

不幸的是,浏览器要么需要很长时间才能完成任务(在FF 10上约为3分钟),要么会挂起(Chrome 17).我试图用jQuery和纯JS完成任务.完全没有区别.

Unfortunately, the browser either needs a lots of time to finish the task (~3 minutes on FF 10) or hangs (Chrome 17). I tried to accomplish the task with jQuery and pure JS. No difference at all.

任务可行吗?编写快速高效的JavaScript应该知道些什么?

Is the task feasible? What should I know to write fast and efficient JavaScript?

我将所有选项放在单个字符串中,并使用innerHTML将其放在选择输入中.感谢您的快速回复.

I put all the options to a single string and use innerHTML to put it to the select input. Thanks for such a quick response.

Edit2:我按照Diodeus的建议生成元素.但是,当select元素处于焦点位置时(感谢rlemon),我会加载选项.我相信所有的答案都是非常有帮助的,对于任何有类似问题的人来说可能都是有价值的.谢谢你们.

I generate elements the way suggested by Diodeus. However, I load options when the select element is in focus (thanks rlemon). I believe all the answers are very helpful and might be valuable for anyone having similar problem. Thank you all.

推荐答案

将HTML构造为字符串或单个对象,然后一次性将其全部注入该页面. DOM重写很慢,因为必须为每个插入计算文档重排.

Build up your HTML as a string or single object an inject it all into that page in one go. DOM re-writes are slow because document re-flows must be calculated for each insert.

这篇关于JavaScript性能,同时将大量子代添加到大量元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆