-3

This question is different because I'm asking between two distinct codes.

If you had to choose between these, which would you choose and why?

1st:

<script>
  var preloadImg = new Image(266, 266);
  preloadImg.src = 'http://via.placeholder.com/266x266';
</script>

2nd:

 <img src="http://via.placeholder.com/266x266" style="display: none;">
svgcoding
  • 77
  • 7

1 Answers1

1

as you tagged javascript, here is my answer:

I would prefer

<script>
  var preloadImg = new Image(266, 266);
  preloadImg.src = 'http://via.placeholder.com/266x266';
</script>

as then you can later use the preloadImg variable, whereas if you did it with html, you would have to go through unnecessary steps to cache the image into a javascript variable

uses of this for example might be drawing on a canvas, and there are many more - javascript is awesome

However, one tiny reason (which should not be accepted) to use the html preloading is for browsers without javascript, or with javascript disabled, as the option is pure html

Hope this helps (I prefer the javascript method)

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
notrota
  • 1,048
  • 10
  • 21