GET image/gif with jQuery

Asked

Viewed 237 times

0

I tried this but the Google Chrome Developers utility recognizes dataType as xhr

$(document).ready(function() { 
        $.ajax({
            type: "GET",
            url: "/img/img.gif",
            dataType: "image/gif",
            cache: true
        });
});
  • Can you explain how you are going to use this image? you want to show on the page or upload the image content somewhere?

  • I want the image to load when the page loads, I won’t use it in html.

  • Why don’t you put the image in HTML with display: none; and then show the image when the page is loaded? This AJAX will fetch the image url?

  • I just want to cache it automatically

1 answer

2


Kevin, Good night.

In reality when you make an ajax request, through a $.ajax, $.post, $.get, the requests will always be an XHR, but the content of the response can be a datatype: jpeg, gif, png, text/html, etc.

Developer Tools, shows the type of request he is making when fired through the src of a Image, he understands that you are carrying an image.

When you request through an object XHR (XMLHttpRequest), he understands that he is a AJAX, therefore appears in the XHR tab.

In practice:

//Vai em network -> Images
var img = new Image();
img.src = "http://images.forbes.com/media/lists/companies/google_416x416.jpg";


//Vai aparecer em network -> XHR
$.ajax({
	type: "GET",
	url: "http://images.forbes.com/media/lists/companies/google_416x416.jpg",
	dataType: "image/jpg",
	cache: true
});

Answer 2:

To cache an image, the best alternative is to use the Expires Header, if you are using Apache, you can search this link:

http://httpd.apache.org/docs/2.2/mod/mod_expires.html

  • You basically did what I did... The content is not encoded in gif..

  • Yes, the idea was to illustrate where each request appeared in the Network tab of Google Developer Tools. But now I understand that what you want, is to add a cache configuration to your image, so I added a second answer.

  • 1

    I want those who do not or yes have the image cached, get as soon as you enter the site, with expires header tb is possible?

  • Yes, using apache expires mod you can set a cache period for each file type. So who n has the file in the cache will now have..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.