Jump to content

use single var for multiple new Image()


Recommended Posts


I was testing to see if I could use the following code to store new Image() in a variable and use it for several images.

var _new_image = new Image();

var _image_1 = _new_image;
_image_1.src = "./assets/views/image_1.jpg";

var _image_2 = _new_image;
_image_2.src = "./assets/views/image_2.jpg";

var _image_3 = _new_image;
_image_3.src = "./assets/views/image_3.jpg";

So each new image created uses the _new_image variable instead of new Image() . But, of course, this isn't working. Only one image will load.

So I was wondering if I can store new Image() in a variable and what the syntax/code would be to do this.





Link to comment
Share on other sites

After  var _image_1 = _new_image; ,_image_1 and _new_image will refer to the same object. When you assign an object, the object is not cloned in JS. In the end you will have only one object of Image type and its src will be  "./assets/views/image_3.jpg" ; The browser will not load the image before that function ends. You can change src after the first image loads:


var _new_image = new Image();

_new_image.src = "./assets/views/image_1.jpg";

_new_image.onload = function (e) {
    _new_image.src = "./assets/views/image_2.jpg";

    _new_image.onload = function (e) {
        _new_image.src = "./assets/views/image_3.jpg";
        _new_image.onload = ....;

I don't think you need this though, you should probably just create an array of Image-s.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...