Google 具有多个 JavaScript 文件的 PageSpeed Insights

Google PageSpeed Insights with Multiple JavaScript Files

我正在根据 Google 的 PageSpeed Insights 优化我的网站。它建议我 "Remove Render-Blocking JavaScript" 几个文件(为示例起见简化名称):

<script src="js/1.js" type="text/javascript"></script>
<script src="js/2.js" type="text/javascript"></script>
<script src="js/3.js" type="text/javascript"></script>

我正在尝试 Patrick Sexton's "Defer Loading Javascript" approach,它只延迟一个文件 (defer.js):

<script type="text/javascript">
  function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild(element);
  }
  if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

我的问题是,如何修改此方法以包含多个文件(即 1.js2.js3.js)?

你可以使用 HeadJS 为了这。我在我们的一个项目中使用它,它非常有用。

<script type="text/javascript">
    function downloadJSAtOnload() {
        var links = ["js/1.js", "js/2.js", "js/3.js"],
            headElement = document.getElementsByTagName("head")[0],
            linkElement, i;
        for (i = 0; i < links.length; i++) {
            linkElement = document.createElement("script");
            linkElement.src = links[i];
            headElement.appendChild(linkElement);
        }
    }
    if (window.addEventListener)
        window.addEventListener("load", downloadJSAtOnload, false);
    else if (window.attachEvent)
        window.attachEvent("onload", downloadJSAtOnload);
    else window.onload = downloadJSAtOnload;
</script>