I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code:
<div class='liveExample'>
<div class="row">
<div data-bind="foreach: items">
<div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
<img data-bind=" attr: { src: $data }" class="lazy" />
</div>
</div>
</div>
</div>
Javascript:
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
bind(this); // Ensure that "this" is always this view model
};
var pictures = []; //Initialise an empty array
for (var i = 0; i = 10 ; i++) {
var image; //This is a placeholder
image = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the src attribute (imageFiles[i] is the current filename in the loop)
pictures.push(image); //Append the new image into the pictures array
}
ko.applyBindings(new SimpleListModel(pictures));
Check out the implementation on jsfiddle