Use javascript to implement lazy-loading for images

Looking to enhance website performance by lazy loading images. Plan is to initially display a set number of images and then load the rest lazily. Here's what I have currently:

Check out the code here


 <div> <img src="http://i.imgur.com/CmU3tnl.jpg"> 1 </div>
 <div> <img src="http://i.imgur.com/TDdxS9H.png"> 2 </div>
 <div> <img src="http://i.imgur.com/39rpmwB.jpg"> 3 </div>
 <div> <img src="http://i.imgur.com/1lBZQ1B.png"> 4 </div>
 <div> <img src="https://i.imgur.com/Y5Ld4Qfh.jpg"> 5 </div>
 <div> <img src="http://i.imgur.com/8HumESY.jpg"> 6 </div>
 ...

 <a href="#" id="loadMore">Load More</a>

 body {
    background-color: #f6f6f6;
    width: 400px;
    margin: 60px auto;
    margin-top: 5px;
    font: normal 13px/100% sans-serif;
    color: #444;
 }
 img{
    width:30px;
    height:30px;
 }
 ...
 (function() {
    var divElements = [].slice.call(document.querySelectorAll("div"));
    var loadMore = document.querySelector('#loadMore');
    var divNumber = 2;

    loadMore.addEventListener('click', function(e) {
        e.preventDefault();
        for (var i = 0; i < divNumber; i++) {
            window.scrollTo(0,document.body.scrollHeight);
            if (i < divElements.length) {
                divElements[i].style.display = 'block';
            }

            if (i >= divElements.length) {
                loadMore.innerHTML = "Load Completed";
                return;
            }
        }
        divElements.splice(0, divNumber);

    });
})();
loadMore.click();

Answer №1

One way to manage image URLs is by storing them in a JavaScript array. This allows you to easily retrieve the next set of image URLs when a user clicks on a "load more" button. Using JavaScript, you can dynamically create an img element by running the code

var elem = document.createElement("img");
and then setting the src attribute to the URL stored in your array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the image link from a Flickr JSon Feed

I'm currently displaying images from a flickr feed on my webpage. Everything is working well, but when I click on an image, it takes me to the page where the image is hosted. What I want is for the images to link directly to the image itself, not th ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

How to add an external JavaScript file to a nuxt.js webpage

Need some help with a simple query. I'm looking to incorporate this widget code from CodePen into my Nuxt.js project. The code works fine when using RAW HTML: <!DOCTYPE html> <html> <head></head> <body> <dev-widge ...

What is the method to determine the folder name of the currently activeTextEditor in VSCode?

Discovering the precise workspace directory of the existing activeTextEditor: let editor = vscode.window.activeTextEditor if (!editor) { vscode.window.showInformationMessage('editor does not exist') return } const path = editor.document.uri. ...

Utilizing Mootools to Access and Obtain the Current Query String Parameters

Is there a way to extract the current querystring values using mootools? I have implemented mootools ajax for php pagination. The initial call includes the following parameters: format=html&nolayout=true&p[0]=1000-1500&p[1]=1500-2000&p[2] ...

Using Angular 6 to load external HTML files with CSS inside a router-outlet

I'm currently working on creating a json-based dynamic template using Angular 6. There are certain scenarios where I need to fetch external html content (which could be stored in a database) along with its corresponding css (also stored separately in ...

The process of retrieving child data from a JSON object

I have a JSON object that I am attempting to iterate through, which is being returned via a Netsuite script. The JSON object contains some child elements. I am specifically trying to access the caption for data under "classnoheirachy - name", but I am un ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

Exploring the isolate scope within a compiled directive

I successfully managed to compile a directive using this piece of code: let element, $injector, $compile, link, scope; element = angular.element(document.getElementById(#whatever)); $injector = element.injector(); $compile = $injector.get('$compile& ...

javascript, issues with floating and displaying elements

I am currently working on creating a JavaScript menu that has a click function to smoothly slide up and down. Although the JavaScript code appears to be functioning correctly, it seems that there is some interference with the CSS. Despite attempting vario ...

Having a tough time navigating promises and async functions within React development

Currently, I am working on a React project that involves a function responsible for fetching paginated data in a recursive manner. This function is nested within another function where the loading screen is triggered at the beginning using showLoading(), f ...

How can you make a Tempory Drawer wider in Material Components Web?

Increasing the Width of a Temporary Drawer in Material-components-web Greetings! I am currently facing an issue with Material-components-web In the provided demo here, I would like to extend the width of the Temporary drawer to accommodate additional co ...

What is the best way to load the route calculation dynamically?

I am struggling with calculating the Google Maps route dynamically. The console shows an error stating that 'calcularRuta' is not defined: Uncaught ReferenceError: calcularRuta is not defined at HTMLInputElement.onclick (index.html:1) Despi ...

New example of how to use the "useSession" syntax in Next Auth

Currently, I am delving into the next-auth documentation and feeling perplexed by the syntax used in the useSession hook. The way it's showcased in the documentation is as follows: const { data: session, status } = useSession() My confusion stems f ...

Unraveling the Mysteries Behind the .next() Method in Angular

import { Component, Input, Output, EventEmitter } from '@angular/core'; var customInputCss = "app/css/ui/custom-input.css"; var customInputTemplate = "app/partials/custom-input.html"; @Component({ selector: 'custom-input', sty ...

Retrieving user information from the database and adding it to the specified element

I've been grappling with what seems like a simple question for the past hour. Below is a script that I have which pulls all active reservations from the reservations table. require("../includes/connect.php"); function dispAllReservations(){ $i= ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...

Exploring the possibilities with Polymer and three.js

I've been attempting to integrate a three.js demo from http://jsfiddle.net/hfj7gm6t/ into my polymer app, but I'm encountering an error message: com-model-viewer.html:33 Uncaught TypeError: Cannot read property 'myview' of undefined ...

Performing a MongoDB query in a controller using the MEAN stack with Node.js

My goal with this controller is to retrieve all the results of a collection. Despite having one item in the prop collection, I am encountering an undefined error. Error: Cannot call method 'find' of undefined This snippet shows my server.js fil ...

What is the method for ensuring that a GreaseMonkey script impacts elements on a page prior to their appearance?

I'm currently working on a project that requires hiding images on a specific website while still displaying the alt text. Initially, I tried to achieve this using Stylish on Firefox and posted the following question: How to force an image's alt ...