I already have a loaded image in the DOM referenced by the variable img
.
I want to set the background image of an element to the loaded image in the DOM.
if i simply do "background-image:url('"+img.src+"')" problem is this relies on whether the image is cached by the browser (for user agents that explicitly do not store cache, or cache max size 0, basically, screwed)
If the image is not cached by the browser, a new image would be requested (which obviously is what I'm trying to prevent since the image is already in the dom re-requesting it is just unnecessary)
how do we set the background image of an element with an already loaded image in the DOM?
Simple test script to prove that the image would be re-requested, (use a browser which you can clear the cache on to test) http://qweop.com/test/cache.php:
<!doctype html><html>
<head></head>
<body onload="load();" >
Step 0. Open your network inspector.<br>
Step 1. Wait for image to finish loading.<br>
Step 2. Clear your browser's cache (do not refresh this page);<br>
<button disabled="disabled" id="button" onclick="
document.getElementById('div').style.backgroundImage='url('+document.getElementById('img').src+')';
">Step 3. After Cache is cleared, click</button>
<br>
<img id="img" width="500" height="500" src="http://upload.wikimedia.org/wikipedia/commons/archive/4/4e/20090223155149!Pleiades_large.jpg" onload="
document.getElementById('button').disabled='';"
/>
<div id="div" style="display:inline-block;width:500px;height:500px;background-color:yellow;"></div>
</body>
</html>