- 那么让我们假设有一篇文章有多个照片库。
- 每个图库中的照片都排列在一个复杂的网格中,只需通过 JS 即可构建。
- JS 的大小小于 ~1KB(gzipped)。
- 第一个画廊可能在首屏。
- 我正在努力让包含这些画廊的页面尽可能快地加载(优化 critical rendering path ),并避免出现无样式的内容(当画廊没有样式时)。
这是我现在所在的位置,HTML:
<div id="first" class="mygallery">...images markup...</div>
<script>
/* Inline full JS code required for gallery (~1KB) */
var gallery = function(id) {
...
};
gallery('#first');
</script>
<p>Some other content of any length.</p>
<div id="second" class="mygallery">...</div>
<script>
/* just init gallery using code from the first one */
gallery('#second');
</script>
<p>Some other content of any length.</p>
<div id="third" class="mygallery">...</div>
<script>
/* just init gallery using code from the first one */
gallery('#third');
</script>
etc...
我的问题:
- 我应该在其元素之后直接初始化画廊,还是应该一次初始化所有画廊(在最后一个画廊 DOM 元素之后,或在
document.ready
中)? - 我是否应该通过
display:none
隐藏所有画廊,然后通过 JS 显示它们以避免 FOUC? (对于非 js 用户,我可以添加样式为display:block;
的 noscript 标签) - 我是否应该内联 JS,~1KB 的 gzip 压缩 js 是不是太多了?
此外,应该注意的是,在执行 gallery()
方法时,会调用一次 getComputedStyle()
(触发布局),然后应用样式(这触发油漆)。这会影响您回答第一个问题吗?
最佳答案
Should I init the gallery directly after its element, or should I init all galleries at once (after the last gallery DOM element, or in document.ready)?
如果目标是减少浏览器为获取屏幕上的像素而必须做的工作量,那么逐步地并根据需要初始化每个像素可能是有意义的 - 例如只有第一个画廊并延迟初始化其他画廊,直到稍后。
Should I hide all galleries via display:none and then reveal them via JS to avoid FOUC? (for no-js users I can add noscript tag with style display:block;)
为了获得最佳效果,请预先为图库预留空间:这样可以最大限度地减少布局回流,并消除页面在内容加载时上下移动的烦人行为。更多信息,请参阅:https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing?hl=en
Should I inline JS at all, isn't ~1KB of gzipped js too much?
这个问题的答案取决于很多变数。如果它引入额外的 RTT,它可能会“太多”——例如超过新 TCP 连接的第一个 RTT 允许的初始 14KB 有效载荷。另一方面,如果这不是问题,那么 1KB 就可以了。另外,考虑对缓存+失效的影响——例如多个页面使用此代码段还是仅使用一个代码段,代码段需要更改的频率以及这是否会影响嵌入它的页面的缓存生命周期等。
关于javascript - 如何内联页面布局多个部分需要的JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088837/