如何内联页面布局多个部分需要的JS?

How to inline JS that is required for multiple parts of page layout?

这是我现在所在的位置,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...

我的问题:

  1. 我应该在其元素之后直接初始化画廊,还是应该一次初始化所有画廊(在最后一个画廊 DOM 元素之后,或在 document.ready 中)?
  2. 我是否应该通过 display:none 隐藏所有画廊,然后通过 JS 显示它们以避免 FOUC? (对于非 js 用户,我可以添加样式为 display:block; 的 noscript 标签)
  3. 我是否应该内联 JS,~1KB 的 gzipped 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;)

为了获得最佳效果,请预先为图库保留 space:这会最大限度地减少布局回流,并消除页面在内容加载时上下移动的烦人行为。更多信息,请参阅: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,它可能是 "too much" - 例如超过新 TCP 连接的第一个 RTT 允许的初始 14KB 有效载荷。另一方面,如果这不是问题,那么 1KB 就可以了。另外,考虑对缓存+失效的影响——例如多个页面使用此代码段还是仅使用一个代码段,代码段需要多久更改一次,这是否会影响嵌入它的页面的缓存寿命等。