Dynamic Image Loading For Adaptive Designs
For our new website we use some large images.
I wanted to optimize how we sent those images down the pipe to the users.
Why push them a 700k image when they did not need it?
Little did I know I would be going down a rabbit hole.
The first method that was quickly dismissed was simply swapping the background url with the high resolution one.
The issue with this was that there was a flash of white during the src swap along with the high resolution image loading in a progressive fashion, which was totally not acceptable.
This approach was more inline with what i wanted. But there still was that nasty flash of white when swapping the background on the elements.
The last method (that ended up being successful) was to load the image via JS but instead of swapping the background image I appended a new DOM node within the parent and gave it a background image css property. This ended up removing the flash of white.
Here is a quick demo of the different methods I tried:
In the end the best option was to append a new dom node within the holder element after loading the image via JS. The reason why this works you may ask?
Well it is simple. Changing the background url is not instant thus causing that white flash. So by simply appending a DOM node, that blank time is replaced by still showing the low res version of the background until the high res version is loaded and inserted into the dom. Simply put, in the third method we never unload the low res image from the dom like we do in the first two methods.
Hope this helps.
-Sam Saccone @samccone