开发者

how do we set the background image of an element with an already loaded image in the DOM?

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开发者_Go百科 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>


You can download the image as a base64 string for the .src of your img instance. Copying the img.src to background-image:url will copy this data-string of the image instead of checking the cache or downloading it. For example:

<img src = "data:image/gif;base64, SOMEBASE64STRING" />

You can get a base64 version of your image here, generate it with PHP like here, or work with the canvas element to generate the base64 string from an image as explained here.


Have you considered loading the image with CSS in the first place?


edit

I think you won't be able to bypass this in a "clean" way. Think like we're going to do a web browser. You make a request, store the image somwhere and use it. What's on the scren is just a rendered version of the file you stored. Once you clear the cache, the browser has to request it again unless it store it somewherelse, like a tmp folder or something (where the user can't delete).

But i guess this isn't a big issue since it's not usual for users to clear the cache on the fly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜