Mohammad
Mohammad

Reputation: 7418

How to speed up sequential JQuery load() requests to the Same div

i have two links

<a href="page1.html">page 1</a>
<a href="page2.html">page 2</a>

<div id="content">&nbsp;</div>

1. I use JQuery to load them into a Div when the links are clicked.

$('#content').load('page1.html');

2. When the second link is clicked I empty the div

$('#content').html('');

3. and load the second file in;

$('#content').load('page2.html');

The problem, page1.html has alot of images in it, even after the second link is clicked and the #content div is emptied, the browser keeps downloading the images from page1.html and this slows down the request to page2.html significantly.

How can i stop the content from the first load() from making requests to the browser and speed up the page response?

Thank you infinity!

Upvotes: 2

Views: 3814

Answers (3)

Imagist
Imagist

Reputation: 18514

Would it be possible to un-AJAX-ify this page? Most browsers I know of stop loading a page (page1) when they leave it. The whole point of AJAX is to make responsive web applications. In this case AJAX seems to be counterproductive toward that goal. My guess is that re-loading all of the content in the page besides the content in the #content div would be faster than finishing loading page1.

Upvotes: 0

Andy Gaskell
Andy Gaskell

Reputation: 31761

I don't think you'll be able to use load. I think you'll need to use the ajax function.

From the docs:

$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.

It's more code, but shouldn't be that bad. You will probably need to tweak this code (it's untested), but I think the concept will work.

var xhr;

$("a").click(function() { 
  if(xhr !== undefined) { xhr.abort(); } 
  xhr = $.ajax({
    url: this.href,
    success: function(data) {
       $("#content").html(data);
    }
  });
});

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532435

I suspect that the problem isn't with the load() method, but rather the requests that are generated when the DOM is updated as a result of the load request completing. Once the requests for the images have been initiated I don't think there is any way short of reloading the page that you can stop those requests from being handled. You could, potentially, check to see if the request has been handled yet when the second link is clicked and reload the page rather than use AJAX if the request is still in progress. I'm not sure this is really worth it though.

Upvotes: 1

Related Questions