0

I'm just looking for confirmation on an question I haven't seen directly answered.

I am building a site and I'd like to load many image urls into a Javascript array without actually sending the images to the browser. To cut down on server bandwidth usage, I'd like to store the URLs in the document and only load them one at a time when the user takes a specific action to do so.

I suppose my question is the opposite of the many "how do I use Javascript to pre-load an image" question like the one found here. The prevalence of these questions suggests that it's safe to stick the urls in a Javascript array at the top of the document and the browser will not automatically pre-load them. Is my assumption correct?

Community
  • 1
  • 1
Nate Vaughan
  • 3,471
  • 4
  • 29
  • 47
  • 1
    You could directly answer this question by testing it. – Evan Davis Nov 22 '14 at 00:59
  • How? I may be a dunce, but I have no idea how to tell if a browser has loaded an image in the background. The images are relatively small, and I am serving them from my own computer, so load time doesn't give me many clues. – Nate Vaughan Nov 22 '14 at 01:15
  • Its a valid question, no everybody know from the fact how a browser render and how to browser behave. So its fair to ask if you dont know it, and also he did research. so totally valid SO question – ncubica Nov 22 '14 at 01:42

3 Answers3

1

Yes the images are non load because you have them as strings in an javascriptarray, the browser never request the images.

I guess you want to do something like:

var myimages = ['{url}','{url}','{url}'];

then you can do something like:

$(document).on("click",".somebutton",function(){
  for(var i = 0, len = myimages.lenght; i++){
     //i will assume you will detect the element depending the situation and its a image element
     $("someSelector").attr("src",myimages[i]);
  }
});

And that way you will request the image from your server in that exact moment.

//using jquery

ncubica
  • 8,169
  • 9
  • 54
  • 72
0

No, images in an array will not be loaded until they are requested by the script. Therefore you could store it in a variable like this:

var imgSrcs = ["http://placekitten.com/g/300/200","http://placekitten.com/1000/1000"]

function getSrc(element,value){
  
  element.src = imgSrcs[value];
  
  }
<img onclick="getSrc(this,'0')" src="#"/>

And load the image when it's clicked on, or something like that.

I hope this helps!

Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
0

A url on its own, in the form of a string will not pre-load anything. You can place an array of strings wherever you like, without worrying about images pre-loading.

If you want to load one, you can create an image and assign a url to its 'src' property.

var image = new Image();
image.src = "http://www.example.com/image/url.jpg";
Christopher
  • 404
  • 2
  • 9