I'm using this code to dynamically load external pages
$(function() {
$('#nav a').click(function() {
var page = $(this).attr('href');
$('#content').load(page + '.php');
return false;
});
});
I've noticed that each time I click on one of the menu tabs, a new HTTP request is sent and the page is loaded again. I'm wondering how to make each page load once so when I go through the tabs, the pages that have been already loaded display without sending new requets ?
You could "tag" tabs that are already loaded with a flag using .data() and only issue the HTTP request when the tag is non-existent.
Edit: Regarding Kryptonite's comment this would be a simple approach to the problem:
var pages = {};
$(function() {
$('#nav a').click(function() {
var page = $(this).attr('href');
if (!(page in pages)) {
$.get(page, function (data) {
pages[page] = data;
});
}
$('#content').html(pages[page]);
return false;
});
});
$('#nav a').click(function(e) {
e.preventDefault();
$this = $(this);
if ($this.data('loaded') !== true) {
// Load it.
$this.data('loaded', true);
} else {
alert('Already loaded that one!');
}
});
This will do what you need. You'll need to throw your load code in where I have the // Load it.
comment, and might want to remove the else
block as well. http://jsfiddle.net/rRumK/