search
HomeWeb Front-endFront-end Q&AWhat are the methods for lazy loading of images?

What are the methods for lazy loading of images?

Nov 13, 2023 pm 02:41 PM
Lazy loading of images

The methods for lazy loading of images include lazy loading based on Intersection Observer, lazy loading using scroll event monitoring, and lazy loading using setTimeout. Detailed introduction: 1. Lazy loading based on Intersection Observer. Intersection Observer is an API provided by the browser, which can monitor whether an element enters the user's viewport; 2. Lazy loading using scroll event monitoring, which is judged by monitoring scroll events. etc.

What are the methods for lazy loading of images?

The operating system for this tutorial: Windows 10 system, DELL G3 computer.

Image lazy loading is a technique for optimizing web page performance. It delays the loading of images on the page and loads them only when the images are about to appear in the user's viewport. This reduces page load times and improves user experience and overall website performance. In this article, I will introduce several commonly used lazy loading methods for images.

1. Lazy loading based on Intersection Observer:

Intersection Observer is an API provided by the browser that can monitor whether an element enters the user's viewport. By using the Intersection Observer, we can monitor whether image elements are visible and load them when the image enters the viewport. This method is not only simple and easy to use, but also has better performance.

The following is a sample code that uses Intersection Observer to implement lazy loading of images:

// 创建一个Intersection Observer实例
const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // 当图片进入视口时加载它
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  });
});
// 获取所有需要懒加载的图片元素,并添加观察者
const lazyImages = document.querySelectorAll('.lazy');
lazyImages.forEach((lazyImage) => {
  observer.observe(lazyImage);
});

2. Lazy loading using scroll event monitoring:

This method is by monitoring scrolling event to determine whether the picture enters the viewport. As the user scrolls the page, check whether the position of each image is in the viewport, and if so, load the image.

The following is a sample code that uses scroll event listening to implement lazy loading of images:

window.addEventListener('scroll', () => {
  const lazyImages = document.querySelectorAll('.lazy');
  lazyImages.forEach((lazyImage) => {
    if (lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) {
      lazyImage.src = lazyImage.dataset.src;
      lazyImage.classList.remove(&#39;lazy&#39;);
    }
  });
});

3. Lazy loading using setTimeout:

This method is to set a delay Time to load images. When the page is loaded, first load a placeholder image, and then use setTimeout to delay loading of the real image to achieve the lazy loading effect.

The following is a sample code that uses setTimeout to implement lazy loading of images:

window.addEventListener(&#39;load&#39;, () => {
  const lazyImages = document.querySelectorAll(&#39;.lazy&#39;);
  lazyImages.forEach((lazyImage) => {
    lazyImage.src = lazyImage.dataset.placeholder;
    setTimeout(() => {
      lazyImage.src = lazyImage.dataset.src;
      lazyImage.classList.remove(&#39;lazy&#39;);
    }, 1000); // 设置延迟时间,单位为毫秒
  });
});

Summary:

Lazy loading of images is an effective way to optimize web page performance and can reduce Page loading time and improved user experience. This article introduces several commonly used lazy loading methods for images, including lazy loading based on Intersection Observer, lazy loading using scroll event monitoring, and lazy loading using setTimeout. Developers can choose a method that suits them based on actual needs to implement lazy loading of images.

The above is the detailed content of What are the methods for lazy loading of images?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),