SoFunction
Updated on 2025-04-14

Detailed explanation of JavaScript laziness loading optimization techniques

This is a dinner talk by a friend before. He was responsible for an e-commerce project he was responsible for. He had just developed tens of thousands of yuan. The homepage loading time was very long and the experience was very poor. So he started to check and found that it was caused by loading all js at one time on the homepage. This problem was not obvious when he was learning. It is often called a programming habit. Some company bosses even made hard regulations or encapsulation of project framework levels, which can play a good role, but today I will share it with you:

Scene description

The website loads JavaScript resources for all modules at once on the homepage, including:

  • First screen carousel
  • Product recommendation list
  • User Comment Module
  • Footer Help Center
  • Advertising and marketing components in unvisible areas

Sample code

// Question code example - load all scripts synchronouslyimport Carousel from './components/Carousel';       // The first screen is necessaryimport ProductList from './components/ProductList'; // The first screen is necessaryimport Reviews from './components/Reviews';         // Need to scroll to the middle to displayimport Ads from './components/Ads';                // Only displayed at the end of the pageimport HelpCenter from './components/HelpCenter';  // Footer folding area​
function HomePage() {
  return (
    <>
      <Carousel />
      <ProductList />
      <Reviews />
      <Ads />
      <HelpCenter />
    </>
  );
}

question

1. The loading time of the first screen is too long

Users need to wait for all JS to download and execute before they can see the content on the first screen

The "First Contentful Paint" indicator in Lighthouse score is very poor

2. Bandwidth waste

Loading resources that the user may never see (such as the bottom content that is not scrolled)

3. Main thread blocking

A large number of JS synchronous execution causes the main thread to be busy for a long time

User interaction (such as clicking on the search box) delay

4. The memory usage is too high

Initialize all components, including those that do not need to be displayed immediately

Check the idea

This troubleshooting idea is very common. Most performance problems can be started here. If you are a new friend of the front-end, it is recommended that you follow the following troubleshooting idea to see your own code execution steps, and then think about it, and you will get unexpected gains.

1. Preliminary performance evaluation

Open Chrome DevTools (F12)

  • Switch to Network panel
  • Check Disable cache (simulate first visit)
  • Select Fast 3G network speed limit (magnification issue)

Recording and loading process

  • Refresh the page and start recording
  • Observe the loading order and timeline of all resources

2. Network panel analysis

JS loading problem identification

Filter JS resources by type

examine:

  • Is it not needed for the first screen to load prematurely
  • Is there a large volume JS blocking rendering (red strips)
  • Whether JS files are loaded in parallel

View key metrics

- Search in Waterfall stream:
* Blue vertical line (DOMContentLoaded)
* Red vertical line (Load)
- focus on:
* The completion time of first screen rendering
* The period of time when the main thread is blocked by JS execution

3. Performance panel depth analysis

Performance panel recording

  • Click Record to refresh the page
  • Check the timeline after stopping

Key area inspection

Main thread activity:

  • Long mission (yellow blocks over 50ms)
  • JS Compilation and Execution (Purple Part)

Network network request:

The relationship between JS loading and execution

Timings Tags:

Key time points such as FP/FCP/FMP/LCP

Typical problem pattern recognition

// Question feature example timeline:
[JS Download 1][JS Execution 1][JS Download 2][JS Execution 2]...
// After optimization, it should be:
[First screen JS download][First screen rendering][Lazy loading other resources]

4. Memory panel check

Memory panel snapshot

Compare Heap snapshot:

  • When the page just loaded
  • After scrolling to the bottom

Memory problem identification

  • Check if unnecessary components are initialized too early
  • Check whether the number of retained DOM nodes is abnormal

Automated audit

Generate a report

  • Switch to the Lighthouse panel
  • Check the Performance option
  • Click Generate report

Key indicators to follow

- Suggestions in Opportunities:
  * "Defer offscreen images"
  * "Reduce unused JavaScript"
- Diagnostics:
  * "Avoid enormous network payloads"
  * "JavaScript execution time"

6. Specific problem positioning steps

Determine the critical rendering path

In Performance Recording:

  • Find FCP (First Contentful Paint)
  • Analyze all previous JS activities

Identify non-essential JS

// Execute in Console:('resource')
  .filter(r =>  === 'script')
  .sort((a,b) =>  - )
  .map(r => ({
    name: ('/').pop(),
    start: ,
    duration: 
  }))

Loading order visualization

Timing diagram using Network:

  • Drag to select the first screen time period (0-FCP)
  • Right click → "Save as HAR with content"

Try to solve it

The most direct understanding of lazy loading can be to load in order, which is not a very complete operation, but to piece together many details or to pay attention to a habit of your daily attention. Here are my habitual ideas:

1. Dynamic Import

import { lazy, Suspense } from 'react';
​
const Reviews = lazy(() => import('./components/Reviews'));
const Ads = lazy(() => import('./components/Ads'));
const HelpCenter = lazy(() => import('./components/HelpCenter'));
​
function HomePage() {
  return (
    <>
      <Carousel />
      <ProductList />
      <Suspense fallback={<Spinner />}>
        {/* Load when the element enters the viewport */}
        <LazyLoadComponent>
          <Reviews />
        </LazyLoadComponent>
        <LazyLoadComponent>
          <Ads />
        </LazyLoadComponent>
        <LazyLoadComponent>
          <HelpCenter />
        </LazyLoadComponent>
      </Suspense>
    </>
  );
}

2. Intersection Observer implements viewport triggering

// Custom lazy loading componentsconst LazyLoadComponent = ({ children }) => {
  const ref = useRef();
  const [isVisible, setIsVisible] = useState(false);
​
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if () {
          setIsVisible(true);
          ();
        }
      },
      { threshold: 0.1 }
    );
    
    ();
    return () => ();
  }, []);
​
  return <div ref={ref}>{isVisible && children}</div>;
};

3. Picture/iframe lazy loading

<!-- Use nativeloadingproperty -->
<img src="" loading="lazy" alt="Product">
​
<!-- Or useIntersection Observeraccomplish -->
<div class="lazy-image" data-src=""></div>

Performance impact data (simulation)

index Non-lazy loading After lazy load optimization
Home screen loading time 4.2s 1.8s
Total JS volume 1.8MB 650KB (Home Screen)
Lighthouse Performance Rating 48 82
First input delay (FID) 320ms 110ms

These details are often very small, but there are many. Friends are welcome to discuss together.

This is the end of this article about the detailed explanation of JavaScript laziness loading optimization techniques. For more related JavaScript laziness loading optimization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!