Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript download image one time set src of two image tags
    primarykey
    data
    text
    <p>I'm trying to do some performance improvement on a web page that I'm building, and one of the things that I'm doing is, using javascript, downloading an image by creating an <code>Image()</code> object, and settings its <code>src</code> attribute to a given URL.</p> <p>I'm then handling the <code>onload</code> event of that object, and in the handler, I'm using the objects <code>src</code> attribute to set the <code>src</code> attribute of two <code>&lt;img&gt;</code> elements on the page. What I was <em>hoping</em> that would do was only download the image one time, and then use that downloaded image as the <code>src</code> of the two image elements on the page, but that doesn't seem to be what's happening.</p> <p>From what I can tell by viewing Network information using Firebug and Google Chrome dev tools, setting the <code>src</code> attribute of the two image elements on the page appears to result in actually downloading the image twice, once for each set.</p> <p>Its the same image, and its rather large...so the download is time-consuming. Is there a way that I can force the image to only be downloaded once? Here's my code:</p> <pre><code>var image = new Image() image.onload = function () { $('#img1').attr('src', image.src); $('#img2').attr('src', image.src); image = null; } image.src = 'my/image/url'; </code></pre> <p><strong>UPDATE</strong>: This is what is causing me to believe that the image is being downloaded twice. Again...I could be wrong, maybe this is misleading, but if Chrome dev tools is reporting two different "resources" on the Network tab, each with the same path, the same file size, but different timings, wouldn't that indicate that its actually being downloaded twice? Maybe my problem is with the dev tools I'm using, I dunno...</p> <p><img src="https://i.stack.imgur.com/qbL4B.png" alt="enter image description here"></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload