0

I'm swapping the content of a page via jQuery's .load() For example, on page1.html I have:

$('#wrapper').fadeOut(2500, function() {
  $(this).load('page2.html', function() {
      $(this).fadeIn(2500);
  });
});

The page2.html content contains some fairly large images, and I am attempting to preload them on page1.html via $.get():

$.get('img/largeImage1.jpg');
$.get('img/largeImage2.jpg');
// etc...

From everything I've read, I'm doing this correctly. The problem is, in Firefox, when I attempt to display largeImage2.jpg for the first time (it's initially hidden with CSS), it appears ever-so-briefly as a broken image. The broken image isn't present when hardcoding in (or 'preloading' via a different method) the image tag on page2.html, i.e. placing <img src="img/largeImage2.jpg" style="display: none;"> somewhere on the page.

Why doesn't the $.get() method work? Am I doing something wrong? Why does Firefox show a broken image for a fraction of a second before loading it? Is jQuery's .load() emptying out the browser's cache/buffer so my attempts at preloading are useless? What's going on?

daveycroqet
  • 2,667
  • 7
  • 35
  • 61

3 Answers3

1

Is the .get really not working, or is it not working as you think it should?

Usually it is used like

$.get( "ajax/test.html", function( data ) {
  $( "#myId" ).html( data );
  alert( "Load was performed." );
}); 

or jquery's load can be used as

 $("#myId").load ("ajax/test.html");  // to load into the element with id myid
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

I suspect that $.get is not really doing what you think it is. If the image isn't in the DOM somewhere, the browser has no reason to cache it. $.get just gets the resource as an AJAX stream, and doesn't insert it into the DOM.

See this SO answer from some alternative approaches to preloading which seem safer.

Community
  • 1
  • 1
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
1

If you want to preload images, then you can use an algorithm such as the one in this answer and this answer. The idea is to load the images into actual <img> objects which will allow the browser to cache them. And, when preloading like this, you also have to wait until the images are actually loaded before using them. If you do it this way, you can guarantee that the images will display as soon as you insert them into the DOM.

In your code, there are at least two issues:

  1. $.get() may not actually cache them.
  2. You aren't waiting for them to actually be loaded before proceeding.
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I don't think point #2 is so much of an issue: if I understand the OP's question correctly, the images aren't being displayed for at least 2.5 seconds seconds (2.5 s fade out, 2.5 s fade in). It would have to be a pretty big image (or a pretty slow connection) not to load that image in time. – Ethan Brown Feb 17 '14 at 01:23