To apply lazy load for images in your Knockout template, first, make sure that Magento 2 Image Lazy Load extension is installed.
Then insert an image into the HTML template (my-template.html) like this:
<img data-bind="attr: {src: $parent.getPixelUrl(), 'data-original': thumbnail, alt: code_article, loading: 'lazy', width: '165', height: '165' }"/>
Example:
<div class="options-block" data-bind="foreach: getOptionBlocks(), afterRender: initLazyLoad()">
<div class="option-item" data-bind="attr: {'data-sku': sku}">
<div class="image-block">
<img data-bind="attr: {src: $parent.getPixelUrl(), 'data-original': thumbnail, alt: code_article, loading: 'lazy', width: '165', height: '165' }"/>
</div>
</div>
</div>
Your view JS file should look like:
define([
'jquery',
'uiComponent',
'ko',
], function ($, Component, ko) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendor_ExtensionName/my-template'
},
pixelUrl: '',
initialize: function () {
this._super();
//some code here
},
//some code here
initLazyLoad: function () {
if (window.LazyLoad) {
new LazyLoad();
}
},
getPixelUrl: function () {
return this.pixelUrl;
},
//some code here
});