piggy_Yu
piggy_Yu

Reputation: 193

Two ways to load image, why is using ajax faster?

I have two ways for loading a image, to test the loading speed.

First:

var img = document.createElement("img");
var date1 = new Date().getTime();
img.src = "xxx.png";
img.onload = function() {
    var date2 = new Date().getTime();
    var delta = date2 - date1;
};

Second:

var date1 = new Date().getTime();
$.ajax({ url: "xxx.png",
         data: { _s: new Date().getTime(), },
         success: function () {
             var date2 = new Date().getTime();
             var delta = date2 - date1;
         }
       });

The above two ways I've tested many times. The second is 30% slower than the first, but I don't know why. Can anyone tell me why?

Upvotes: 1

Views: 1743

Answers (2)

Ross Patterson
Ross Patterson

Reputation: 9569

Any time you compare a hard-coded browser function (i.e., img.src="xxx.png" loading an image) to a complex JavaScript operation (i.e., $.ajax(almost anything)), the JavaScript code is going to lose. Interpreted scripting languages have a hard time matching the speed of the compiled code they're scripting.

Upvotes: 0

Pointy
Pointy

Reputation: 414046

When you load the file as an image, the browser decodes the ".png" encoding to prepare the image for display. It doesn't call your "load" handler until it knows it's a good image. In the second case, you're just fetching the data, so the browser doesn't care whether it's a valid ".png" file or not.

That's my bet, anyway. I'm pretty sure that if you loaded a random data file (not an image) the first way, your "load" handler would never be called.

edit Well the "mistake" in the original question makes the speculation behind this answer basically worthless. (The original question read that the second — ajax — was faster than loading via a newly-constructed image.)

Upvotes: 2

Related Questions