Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  133] [ 3]  / answers: 1 / hits: 40615  / 13 Years ago, sun, april 17, 2011, 12:00:00



I'm trying to clone an image in javascript, bud without loading a new one.

Normally new browsers will load an image once and there are several ways to use that image again.
The problem is that when I test it in IE 6 the image will request a new image from the server.


Anyone how has some info on how to do this in older browsers?



3 methods that not work:



<html>
<head>
<title>My Image Cloning</title>
<script type=text/javascript>
sourceImage = new Image();
sourceImage.src = myImage.png;

function cloneImageA () {
imageA = new Image();
imageA.src = sourceImage.src;
document.getElementById(content).appendChild(imageA);
}

function cloneImageB () {
imageB = sourceImage.cloneNode(true);
document.getElementById(content).appendChild(imageB);
}

function cloneImageC()
{
var HTML = '<img src=' + sourceImage.src + ' alt= />';
document.getElementById(content).innerHTML += HTML;
}
</script>
</head>
<body>
<div id=controle>
<button onclick=cloneImageA();>Clone method A</button>
<button onclick=cloneImageB();>Clone method B</button>
<button onclick=cloneImageC();>Clone method C</button>
</div>
<div id=content>
Images:<br>
</div>
</body>




Solution



Added cache-headers server-side with a simple .htaccess file in the directory of the image(s):

/img/.htaccess



Header unset Pragma
Header set Cache-Control public, max-age=3600, must-revalidate


All of the above javascript method's will use the image loaded if the cache-headers are set.


More From » image

 Answers
45

Afaik the default browser behavior is to cache images. So something like this should work the way you want:



 var sourceImage = document.createElement('img'),
imgContainer = document.getElementById(content);
sourceImage.src = [some img url];
imgContainer.appendChild(sourceImage);

function cloneImg(){
imgContainer.appendChild(sourceImage.cloneNode(true));
}


It's all pretty sop, so it should run in IE6 too (I don't have it, so can't test that).
See it in action



Furthermore, you may want to check the cache setting of your IE6 browser. I remember from the not so good old days with IE<8 that I sometimes reverted to setting the cache to refresh every time you load the page (or someting like that).


[#92680] Friday, April 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregorio

Total Points: 362
Total Questions: 95
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
gregorio questions
Fri, Apr 8, 22, 00:00, 2 Years ago
Mon, Sep 6, 21, 00:00, 3 Years ago
Sun, Sep 13, 20, 00:00, 4 Years ago
;