6

我正在编写一个单页应用程序。最初提供页面时,它包含许多 DOM 元素,其中包含我要注入页面的 json 字符串。

当页面在客户端加载时,首先发生的事情是这些 DOM 元素从 json 解析为 javascript 对象,然后它们再也不会被使用。

从 DOM 中删除它们并减小其大小是否会带来性能优势?我还没有找到任何关于这方面的确凿数据。有关信息,这些元素的大小约为 500K。

感谢您的建议。

4

2 回答 2

4

从 DOM 中删除它们并减小其大小是否会带来性能优势?

就 DOM 的性能而言,一般来说,与 DOM 交互的次数越少越好。

请记住,您的选择器会遍历 dom,因此如果您使用效率低下的选择器,无论如何都会降低性能,但是如果您尽可能按 ID 而不是类或属性选择元素,则可以从页面中挤出良好的性能,无论您是否删除了那些无关的标记项。

最初提供页面时,它包含许多 DOM 元素,其中包含我要注入到页面中的 json 字符串......对于信息,这些元素的大小约为 500K。

在页面加载方面,您的性能已经因必须传输所有数据而受到影响。如果您能找到一种仅传输 json 的方法,那只会有所帮助。但是,事后删除并不能解决这个特定问题。

于 2012-07-10T22:35:24.477 回答
1

Independent of whether you pull the JSON from the DOM, you might consider this technique for including your JSON objects:

<script type='text/json' id='whatever'>
  { "some": "json" }
</script>

Browsers will completely ignore the contents of those scripts (except of course for embedded strings that look like </script>, which it occurs to me as things a JSON serializer might want to somehow deal with), so you don't risk running into proplems with embedded ampersands and things. That's probably a performance win in and of itself: the browser probably has an easier time looking for the end of the <script> block than it does looking through stuff that it thinks is actual content. You can get the content verbatim with .innerHTML.

于 2012-07-11T00:19:33.373 回答