JohnJohnGa
JohnJohnGa

Reputation: 15685

Url hash fragment format

I need to save the UI state in the hash fragment, I tried two different methods:

1- hash fragment with a query string format

#a=foo&b=bar

and then get a value with a custom function:

getParam: function (parameter) {
    if(document.location.hash !== "") {
        var param = document.location.hash.substring(1).split("&");
        for(var i in param) {
            var keyValue = param[i].split('=');
            if(keyValue.length === 2 && keyValue[0] === parameter) {
                return $.trim(keyValue[1]);
            }
        }
    }
    return null;
}

2- hash fragment with a json object

#{"a":"foo","b":"bar"}

and then get the object with

$.parseJSON(document.location.hash.substring(1))

What is the best methods? Is there a specific convention for the hash fragment format?

Upvotes: 1

Views: 356

Answers (1)

Quentin
Quentin

Reputation: 943556

Best practise is to leave the fragment id alone. Use the history api to change a real query string.

Then, when the page is requested from scratch, build it entirely on the server.

This:

  • Avoids the need to load a base page before immediately replacing large chunks of it with Ajax data (which used to make the Twitter web app horrible to use until they moved to the history api)
  • Makes links friendly for search engines and other non-JS clients

Upvotes: 2

Related Questions