"New Image ()" allows the use of cache (JavaScript)

If I use new Image()to load an image in JavaScript, will it use the cached version, if possible, or will it always download a new copy?

var imgObj = new Image();
imgObj.src = 'http://...';
imgObj.onload = function (loadedImg) { }
+3
source share
3 answers

It will load from the cache if it is there, just like <img>in your markup.

+6
source

It should be noted that if you want it to onloadalways happen (even when it was in the cache), you must specify to . onloadsrc

var imgObj = new Image();
imgObj.onload = function (loadedImg) { }
imgObj.src = 'http://...';
+3
source

, . , URL- src ,

imgObj.src = 'http://www.mySite.com/images/anImage.png';

imgObj.src = 'http://www.mySite.com/images/anImage.png?foo=0';

Just understand that on subsequent downloads, it will still use the cached copy, unless you change the query string argument.

+2
source

Source: https://habr.com/ru/post/1770380/


All Articles