Google PageSpeed Insights显示未使用的JavaScript,但已使用

问题描述

使用了Javascript,但Google Page Speed Insights显示未使用Javascript。无论如何,我可以将其删除。在这里,我分享了PageSpeedInsight报告的屏幕截图。

GPSI

在上面的屏幕截图中,您可以看到8个js文件未使用。但是它正在我的应用程序上使用。

解决方法

您可以滚动加载脚本文件。当用户开始向下滚动时,可以将脚本标签附加到头部,然后再次删除事件侦听器。

仅添加开始时在视口中不可见的脚本,例如recapchas。通常位于底部。

function dynamicLoad(url) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
}
window.addEventListener("scroll",loadScripts);

function loadScripts() {
  //load here as many dynamic scripts as you want
  dynamicLoad("recaptcha url");
  dynamicLoad("facebook.net url");
  //end ------
  window.removeEventListener("scroll",loadScripts);
}
,

注意:此答案是由于混乱。 OP未使用React,但报告包含React示例。这可能对其他人有帮助 无论如何。

如果组件是动态加载的(仅在用户请求之后)。

您可以按照报告中的建议使用React.lazy()进行代码拆分,这样就不必在不需要时加载大捆绑包。

此解决方案适用于非SSR。

之前:

import ComponentB from './ComponentB';

function ComponentA() {
  return (
    <>
        {/* After certain action probably like routes switch or any? */}
        <ComponentB />
    </>
  );
}

之后:

import React,{ lazy } from 'react';
const ComponentB = lazy(() => import("./ComponentB.js"));

function ComponentA() {
  return (
    <>
        {/* After certain action probably like routes switch or any? */}
        <ComponentB />
    </>
  );
}

参考:https://reactjs.org/docs/code-splitting.html

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...