In short, I would like to create a lazy-loaded-mock-image-src-url in browser. This is in order to simulate the loading of an image, to see how it loads.
Here is how I would like the flow to work, all done in-browser.
- Create a URL using URL.createObjectURL, canvas.toDataURL or similar, where the actual image that the returned url refers to, is not loaded yet (just like a real scenario).
- Pass the returned url that refers to the unloaded image to an html-img-tag.
- The image does not (visibly) load in the html-img-tag.
- Trigger a load of the image (that the url refers to) (preferably using some JS function) after some delay.
- The actual image is (visibly) shown in the html-img-tag.
I have managed to create a src string in the browser that refers to an image, that is passed to an html-img-tag, BUT the image loads instantly.
const canvas = document.createElement('canvas');
// ...create the image using getContext, fillRect etc...
const url = canvas.toDataURL('image/png');
How can I make sure the image that the url refers to is not loaded initially?
Is it better to use URL.createObjectURL
or some other method instead?
Is it at all possible?
PS. I don’t want to edit the html-img-tag, using onload method as the img is a 3rd party (react) component.
2
Answers
You can try to progressively pass chunk of the url data to the img tag src attributes.
With modern internet speeds images load in milliseconds, to simulate the loading of an image one possibility is to "partially" draw the image in our canvas, and of course with a canvas we can add a lot of fancy animations, imagination is the limit…
Here is a simple left to right animation we can use to simulate the loading of an image.
Here is another simple animation using blur
You can use the canvas directly as your image instead of an html-img-tag but if you really want to use an image
<img src="." >
the code is simple…after we draw in the canvas we select and add the output of toDataURL