ChrisMurray
ChrisMurray

Reputation: 487

Knockout JS: Image loading

I have a partial with the following code snippet:

#Foreach row in a dataset...
<!-- ko if: $row.myBoolean -->
<div>
  <a href="mylink.html">
    <object width="18" data="/assets/img/MyImage.svg" type="image/svg+xml"></object>
  </a> 
</div>
<!-- /ko -->

It is working as intended from the front end, but when I look at the network traffic I can see the image load is initiating, and then cancelling:

enter image description here

As the dataset can have 1000+ rows, this is having a massive affect performance (the myBoolean almost always returns false).

I am not sure what is going on here. I would expect that the browser would not even try loading the image for rows where myBoolean returns false?

Have I got something wrong, or is this how Knockout works? Is there a better way of doing this?

Upvotes: 0

Views: 193

Answers (1)

user3297291
user3297291

Reputation: 23372

Your HTML is first parsed by the browser. The browser ignores any knockout related mark up. As far as it's concerned, the <!-- ko if: ... --> stuff is just a comment.

Therefore, the moment just before you ko.applyBindings, the browser will try to render the image and start loading it.

Only then, once you call applyBindings and myBoolean is false, knockout will remove the part between the if binding.

The browser will probably then notice the image is no longer needed and cancel its download.

To make sure the images are only needed if the viewmodel wants them to render, I'd advice injecting the data attribute via knockout:

data-bind="attr: { data: '/assets/img/MyImage.svg' }"

Note that it might take longer for images to load, since you're only going to request them once they're actually needed in the view.

Upvotes: 1

Related Questions