Using hash ( #
) is a possible solution.
Changing the hash does not cause the browser to trigger a new request.
You can change the hash in two ways:
Via links:
<a href="#noticias">Notícias</a>
Via Javascript:
window.location.hash = "noticias";
It is possible to trigger an event every time the hash is changed:
// usando jQuery
$(window).on("hashchange", function() {
alert(window.location.hash);
});
If the user directly accesses a hashed URL as:
https://www.seu-site.com/#noticias
The ideal is to create an event that loads the requested content:
// novamente com jQuery
$(document).on("ready", function() {
var pagina = windows.location.hash;
if (pagina === "#noticias") {
// carrega "Notícias"
}
}
To get more DRY, you can create a function that loads the correct page and trigger it in the two events (domready and hashchange):
var carregaPagina = function() {
var pagina = windows.location.hash;
if (pagina === "#noticias") {
// carrega "Notícias"
}
};
$(document).on("ready", carregaPagina);
$(window).on("hashchange", carregaPagina);
I've assembled a basic example in JSFiddle .
About Google Analytics
My Google Analytics experience is zero . But this answer of Stack-EN suggests manually informing the page request in the hashchange
event. I have not tested this but I believe this page tells you exactly how to do that.
There is also the History API
I will not say much about it, because I have never used it in practice. (It would be good for someone with experience to give an answer about it.)
Basically it provides a means of artificially manipulating browser history, in conjunction with the URL, via Javascript, without the need to use the hash. This is a new HTML5 feature, and will not work in legacy browsers:
Usefullinks