How do I enable lazy loading for images in Magento?
Enable Lazy Loading for Images in Magento
Method 1: Using a Third-Party Extension
Step 1: Choose and Install a Lazy Load Extension
-
Find an Extension:
- Go to the Magento Marketplace and search for "lazy load" extensions.
- Some popular options include "Mageplaza Lazy Load," "Amasty Lazy Load," and "MageComp Lazy Load."
-
Purchase and Download the Extension:
- Select an extension that suits your needs.
- Purchase and download the extension package.
-
Install the Extension:
- Upload the extension files to your Magento root directory using FTP/SFTP.
- Run the following commands via SSH in the root directory of your Magento installation:
php bin/magento module:enable [Extension_Name]
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean
Step 2: Configure the Extension
-
Go to the Admin Panel:
- Navigate to
Stores > Configuration > [Your Extension Provider] > Lazy Load
.
-
Configure Settings:
- Enable lazy loading and configure the settings according to your preferences.
- Adjust settings such as image placeholders, loading animations, and any other available options.
Method 2: Custom Implementation Using JavaScript
Step 1: Add Lazysizes Library
-
Download Lazysizes:
-
Upload Lazysizes to Magento:
- Place the
lazysizes.min.js
file in your theme’s web/js
directory.
-
Include Lazysizes in Your Theme:
- Add the following code to your theme’s
requirejs-config.js
file to include the lazysizes library:
var config = {
paths: {
'lazysizes': 'js/lazysizes.min'
},
shim: {
'lazysizes': {
deps: ['jquery']
}
}
};
Step 2: Modify Image Tags
-
Update Image Tags:
- Modify your image tags to use the
data-src
attribute instead of the src
attribute and add the lazyload
class. For example:
<img data-src="path/to/image.jpg" class="lazyload" alt="Your Alt Text" />
-
Add Placeholder Images:
- Optionally, add a low-resolution placeholder image in the
src
attribute to be displayed before the actual image loads:
<img src="path/to/placeholder.jpg" data-src="path/to/image.jpg" class="lazyload" alt="Your Alt Text" />
Step 3: Initialize Lazysizes
-
Ensure Lazysizes Initialization:
- Lazysizes automatically initializes itself, but ensure that your theme includes the necessary initialization code if needed:
require(['jquery', 'lazysizes'], function ($) {
$(document).ready(function () {
// Additional initialization code if necessary
});
});