I am working on a small project in which I want to create an Ajax-style website. Content is loaded with jQuery's load()
. As some of you know, the down side of this is that the URL does not change accordingly to the content that is displayed. To make this work you can use pushState()
. Because this is not cross-browser supported, I used the plug-in history.js
.
This is working quite nicely, but the problem is that my back and forward buttons are not working as they should and I have no idea what I am doing wrong. The URL is changing correctly and the content is as well, but the title is not changing at all. With title I mean what is shown as title of the window (or tab) of the browser window. I.e. the <title>
of the page that is loaded OR the title attribute of the link that refers to that page (they are the same). I think it has to do with the fact that I call only a section of the page whose title I need (i.e. by adding #content
to the load()
). I still want the title of that page though. Here is a test case of what I have up to now. (Not available any more since 28 Dec. 2013.) jQuery file:
$(document).ready(function () {
var firstLink = $("ul > li:first-child > a");
var menuLink = $("ul > li > a");
var firstLoadedHtml = firstLink.attr("href") + " #content";
$("#sectionContainer").hide().load(firstLoadedHtml).fadeIn("fast");
firstLink.addClass("active");
menuLink.click(function(e) {
history.pushState(null, null, this.href);
e.preventDefault();
e.stopImmediatePropagation();
var CurLink = $(this);
var newLoadedHtml = CurLink.attr("href") + " #content";
var oldSection = $(".contentPage");
$("#sectionContainer").hide().load(newLoadedHtml).fadeIn("fast");
menuLink.removeClass("active");
CurLink.addClass("active");
});
$(window).bind('popstate', function() {
var returnLocation = history.location || document.location;
$('#sectionContainer').load(returnLocation + "#content");
});
});
I also noted that when going back to the basic page (i.e. /sectionLoaderTest/) it goes blank for a while and only after a while the content of the first page is loaded. Is there a way to optimize this?
Additionally, I am using jQuery to add an active-class to the link that has been clicked. How can I make sure that this changes accordingly to the history? So that the correct link is highlighted when a user navigates back?
So the three questions are:
- Get the title working when going forward and backward
- Optimize the load time of the mainpage
- Fix the active-class when going forward and backward
All help welcome!
NOTE 1: I would like to build on history.js and my own script and as such keep support for < HTML5
browsers. I would prefer this because 1. I know this has to work, there is just something that's going wrong. 2. It would save time if I could see one's solution and implement it in the script I already wrote rather than figuring out a whole new script.
NOTE 2: The bounty will only be given to he or she who can answer all of my questions (3)!