Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google PageSpeed Insights showing unused javascript but it is used

Javascripts which are used but google page speed insights shows it is not used. Is there anyway the i can remove it. Here i am sharing the screen shot of PageSpeedInsight report.

GPSI

In the above screenshot u can see 8 js files were unused. But it is getting used on my app.

like image 818
Dhanush Kumar Sivaji Avatar asked Jan 25 '23 19:01

Dhanush Kumar Sivaji


2 Answers

NOTE: This answer is due to confusion. The OP is not using React but the report includes the React example. 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.

This solution is for non 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

like image 173
Ashish Yadav Avatar answered Jan 27 '23 08:01

Ashish Yadav


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.

Only add scripts that arent in the viewport at the beginning like 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);
}
like image 28
Ifaruki Avatar answered Jan 27 '23 08:01

Ifaruki