Asynchronously load images with jQuery

JavascriptJqueryAjaxImageJquery Load

Javascript Problem Overview


I want to load external images on my page asynchronously using jQuery and I have tried the following:

$.ajax({ 
   url: "http://somedomain.com/image.jpg", 
   timeout:5000,
   success: function() {

   },
   error: function(r,x) {

   }
});

But it always returns error, is it even possible to load image like this?

I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?

Javascript Solutions


Solution 1 - Javascript

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

     

Solution 2 - Javascript

IF YOU REALLY NEED TO USE AJAX...

I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:

Solution 1

Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>

So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.

$.ajax({ 
	url : 'BASE64_IMAGE_REST_URL', 
	processData : false,
}).always(function(b64data){
	$("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});

Solution2:

Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:

var url = 'IMAGE_URL';
$.ajax({ 
    url : url, 
    cache: true,
    processData : false,
}).always(function(){
    $("#IMAGE_ID").attr("src", url).fadeIn();
});   

However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.

cheers, will

Solution 3 - Javascript

Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.

<img class="loadlater" data-src="path/to/image.ext"/>

A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.

$(document).ready(function(){
    $(".loadlater").each(function(index, element){
    	$(element).attr("src", $(element).attr("data-src"));
    });
});

I bet the jQuery code could be abbreviated, but it is understandable this way.

Solution 4 - Javascript

$(<img />).attr('src','http://somedomain.com/image.jpg');

Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.

Solution 5 - Javascript

You can use a Deferred objects for ASYNC loading.

function load_img_async(source) {
	return $.Deferred (function (task) {
		var image = new Image();
		image.onload = function () {task.resolve(image);}
		image.onerror = function () {task.reject();}
		image.src=source;
	}).promise();
}

$.when(load_img_async(IMAGE_URL)).done(function (image) {
	$(#id).empty().append(image);
});

Please pay attention: image.onload must be before image.src to prevent problems with cache.

Solution 6 - Javascript

If you just want to set the source of the image you can use this.

$("img").attr('src','http://somedomain.com/image.jpg');

Solution 7 - Javascript

This works too ..

var image = new Image();
image.src = 'image url';
image.onload = function(e){
  // functionalities on load
}
$("#img-container").append(image);

Solution 8 - Javascript

AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)

<script>
 $(document).ready(function() {
 $.ajaxSetup({
    cache: false
});
 $("#placeholder").load("PATH TO IMAGE");
   var refreshId = setInterval(function() {
	  $("#placeholder").load("PATH TO IMAGE");
   }, 500);
});
</script>

Solution 9 - Javascript

use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:

$("#img_id").error(function(){
  //$(this).hide();
  //alert("img not loaded");
  //some action you whant here
});

careful - .error() event will not trigger when the src attribute is empty for an image.

Solution 10 - Javascript

$(function () {
       
        if ($('#hdnFromGLMS')[0].value == 'MB9262') {
            $('.clr').append('<img src="~/Images/CDAB_london.jpg">');
        }
        else
        {
            $('.clr').css("display", "none");
            $('#imgIreland').css("display", "block");
            $('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
        }
    });

Solution 11 - Javascript

//Puedes optar por esta solución:

var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                            alert('broken image!');
                        } else {
                        $("#imagenesHub").append(img);
                        }
                    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAriefView Question on Stackoverflow
Solution 1 - Javascriptkarim79View Answer on Stackoverflow
Solution 2 - JavascriptmschmoockView Answer on Stackoverflow
Solution 3 - JavascripththoView Answer on Stackoverflow
Solution 4 - JavascriptJaseemView Answer on Stackoverflow
Solution 5 - JavascriptphpcodingView Answer on Stackoverflow
Solution 6 - JavascriptslobodanView Answer on Stackoverflow
Solution 7 - JavascriptBasilin JoeView Answer on Stackoverflow
Solution 8 - Javascriptbenhowdle89View Answer on Stackoverflow
Solution 9 - JavascriptPoelinca DorinView Answer on Stackoverflow
Solution 10 - JavascriptMadhaviLatha BathiniView Answer on Stackoverflow
Solution 11 - JavascriptJohnUNIView Answer on Stackoverflow