简体   繁体   English

Google PageSpeed Insights 显示未使用 javascript 但已使用

[英]Google PageSpeed Insights showing unused javascript but it is used

Javascripts which are used but google page speed insights shows it is not used.使用的 Javascripts 但 google page speed insights 显示它没有被使用。 Is there anyway the i can remove it.无论如何我可以删除它。 Here i am sharing the screen shot of PageSpeedInsight report.我在这里分享 PageSpeedInsight 报告的屏幕截图。

GPSI

In the above screenshot u can see 8 js files were unused.在上面的截图中,你可以看到 8 个未使用的 js 文件。 But it is getting used on my app.但它正在我的应用程序上使用。

NOTE: This answer is due to confusion.注意:这个答案是由于混淆。 The OP is not using React but the report includes the React example. OP 没有使用 React,但报告中包含 React 示例。 This might be helpful to others anyways.无论如何,这可能对其他人有帮助。

If your components are loaded dynamically ( only after a user request for it ).如果您的组件是动态加载的(仅在用户请求之后)。

You can use React.lazy() as suggested in the report for code splitting so that you don't load the large bundle when not necessary.您可以按照报告中的建议使用React.lazy()进行代码拆分,这样您就不会在不需要时加载大型包。

This solution is for non SSR.此解决方案适用于非 SSR。

BEFORE:前:

import ComponentB from './ComponentB';

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

AFTER:后:

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

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

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

You could load your script files on scroll.您可以将脚本文件加载到滚动条上。 When the user starts to scroll down you append the script tag to your head and remove the event listener again.当用户开始向下滚动 append 脚本标记到你的头部并再次删除事件监听器。

Only add scripts that arent in the viewport at the beginning like recaptchas.仅在开始时添加不在视口中的脚本,如 recaptchas。 The are usually somehwere at the bottom.通常在底部。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM