Window.location.hash Property Introduction

Source: Internet
Author: User
Tags getscript

Window.location.hash Property Introduction

Location is the built-in object that manages the address bar inside JavaScript, such as location.href to manage the URL of the page, and Location.href=url to redirect the page directly to the URL. Location.hash can then be used to get or set the label value of the page. such as http://domain/#admin的location. hash= "#admin". Using this attribute value can make a very meaningful thing.

Many people like to bookmark Web pages for future browsing. However, for the Ajax page, the general use of a page to handle all the transactions, that is, if you browse to an AJAX page inside the interesting content, want to collect it, but only one ah, the next time you open this address, or you have to continue to click on the page as usual, Find the page you love. In addition, the "Forward" and "Back" buttons on the browser will also fail, which is a great barrier to use in many users who are accustomed to traditional pages.

So, how to use Location.hash to solve these two problems? In fact, it is not mysterious.

For example, my author management system, the main functions are three: normal search, advanced search, background management, I assign them a hash value: #search, #advsearch, #admin, when the page is initialized, Use Window.location.hash to determine which pages a user needs to visit, and then use JavaScript to adjust the display page. Like what:

var hash;

Hash= (!window.location.hash)? " #search ": Window.location.hash;

Window.location.hash=hash;

//Adjust the Address bar address so that the forward and backward buttons can be used

Switch(hash) {

Case "#search":

Selectpanel ("Pnlsearch"); //Display normal search panel

break;

Case "#advsearch":

Case "#admin":

}

By Window.location.hash=hash This statement to adjust the address bar address, so that the browser inside the "forward", "back" button can be used normally (essentially deceiving the browser). Then, according to the different hash values to display different panels (users can collect the corresponding panel), which makes the Ajax page browsing tends to be traditional.

Use HTML5 to control the browser address bar and support forward and backward

Now the single page no refresh application, that is, using AJAX to obtain data, through the front-end JS rendering page, the user in a page to complete almost everything. In order for the browser to remember and mark the current page, it is necessary to use the anchor point, or Location.hash, to record the parameters. Because the direct modification of LOCATION.HREF will cause the page to jump. The method described below is a new addition to HTML5, which gives you the freedom to control the browser history so that the address bar really changes instead of the various #.

The following is reproduced:

Original address:

{

' The first paragraph ': ' Http://note.sdo.com/u/1185659399/n/6GXE7~jE5sx0LX0xI000pW ',

' Second paragraph ': ' Http://hi.baidu.com/kooboy/blog/item/6f2c31adadedc2134b36d691.html ',

' Documentation ': ' Https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history '

}

First paragraph

1. What is the problem?

People who may not have written Ajax applications will wonder if it's so hard to change the URL and support backwards? This is indeed a problem at this stage. There are two main points where the problem arises.

1.1 Changing the current URL will let the browser load the page

Javascript has a function to change the current URL path.

window.location = '/'

If you enter this line of code in the console of the browser's Web debugger (Firebug or Chrome native debugging tool), the page immediately jumps to the root of the current Web site. This is the same as if the user clicked on a hyperlink.

If you change the URL only after the # number, it will not cause the browser to reload the page. Because the browser thinks the # number is an anchor point for the current page, there is no need to refresh it.

window.location = ' #here '//will not cause page refresh

This feature is also used later.

1.2 Browsers do not know how to record the state of an Ajax call

Because the AJAX calls are various, the statistics code will cause AJAX, the ad will cause Ajax, the page timed refresh will cause Ajax, so the browser does not know how to record the state of Ajax.

What happens if a user clicks on a link to refresh a page through Ajax and then goes to another page and then points back to the button? The browser will dump the data returned by the last Ajax call intact, which could be JavaScript code, possibly an unhandled JSON data. This is not the case with a mature web site, as developers have handled it in various ways (discussed later). But how do you visit codecampo.com in the evening two days ago, you might see this, because I didn't know how to deal with it at that time. : )

1.3 Goals

Ideally, you should let the Ajax call reach this state:

If the page after the Ajax call is logically not the same as the previous page, then the URL should change.

The premise above, then in the new page click the browser's Back button, should go back to the Ajax call before the page.

Status 1 is for the visitor to be able to place the current page in the Favorites folder, or to share the resource address by copying and pasting the URL; State 2 is to meet the smallest surprises.

2. Current mainstream-single page app that only changes URL Hash

Careful observation can be found that the current Twitter,google,facebook URL address is flooded with #号或者 #! No. For example a new version of the Twitter address is like this

Https://twitter.com/#!/chloerei

This #! What is the meaning of the number? This can take a look at Ruan Feng finishing this article "The URL of the well number." This assumes that you already know that the changes after the # number will not cause the page to load, and how to use this feature to reach the target of 1.3.

2.1 The first step, links to Ajax calls are all used #path as the link target

For example, if a link was originally

<a href= "/TOPICS/1" >topic1</a>

is modified to

<a href= "#/topics/1" >topic1</a>

Obviously, if you don't do the follow-up work, the page will not change when the link is clicked, and the user will not be taken to the new address. The only change is that the # part of the URL becomes a #topics/1

2.2 Setting the Onhashchange event

In the JavaScript API, the Onhashchange event is called when the hash value (the following part of the # Number) of the Window object is changed. Put a function on the Onhashchange, you can call this function when the hash has changed.

For example, you can enter this section of the JS Code test in the console

Window.onhashchange = function () {alert (Window.location.hash)}

The actual function inside is to put the code that is really used to refresh the page. For example, use $.get (Location.path) in JQuery.

2.3 Effects

Now the Twitter,gooogle,facebook use this method to refresh the page, which is also good for browser bookmarks, back support.

But there are some side effects.

One is because the page path is written in the hash, and the browser does not send the hash portion to the server. So open such a URL requires two back and forth: 1, open the blank first page 2, according to the Hash with Ajax loading the actual content

The second is to write the path in the Hash to destroy the original meaning of the URL. From the URL literal view

Https://twitter.com/#!/chloerei

This page represents the!/chloerie anchor point on the Twitter.com page. But from the actual content, this represents the Chloerei personal page. So some people call this site "single page Application". Overall, the programme is highly supportive of mainstream browsers and is currently a mainstream solution.

3. Future scenarios: Based on the history.pushstate API

Let's look at the real-world example: Github. Github's Source Browsing page is an example of Ajax and normal URL changes, and the browser fallback function works as well. You can click on each folder in Https://github.com/chloerei/campo and observe the address bar. But currently only support for HTML5 friendly browsers, such as Chrome, firefox4.

Github has a short log that describes how they implement it: Https://github.com/blog/760-the-tree-slider

Let's analyze it gradually.

3.1 Ways to change URLs without loading pages

The History.pushstate method is added in HTML5 to add history to the browser, but does not trigger page loading. The detailed documentation can be seen here.

The basic usage is to add the visited address to the page history using the Pushstate method while the Ajax is being sent. If you call Ajax in the Ujs-jquery way of Rails, it looks like this (part of the code for the Campo project)

HTML section

<div class= "paginate" ><a href= "/?page=1" data-remote= "true" > Next </a></div>

The Data-remote property is the flag bit that UJS uses to enable Ajax.

JS section

$ ('. Paginate a '). Live (' Ajax:beforesend ', function (event, XHR, Settings) {if (History && history.pushstate) {

History.pushstate (null, Document.title, THIS.HREF);

}

});

This hook method pushes the destination address into the browser's history before sending the AJAX request, so the address bar of the browser is updated without overloading the entire page.

3.2 Processing the Back button

The Onpopstate event is triggered when the browser backs up, so the event should be handled.

if (history && history.pushstate) {

$ (window). Bind ("Popstate", function () {$.getscript (location.href);

});

}

The logic here is similar to the one-page application of the URL Hash, but the difference is that the hashchange is handled, and the popstate is handled here.

3.3 Returning from a non-Ajax page to an AJAX page

After two steps, you can already switch back and forth on the Ajax page, but if you go to a non-Ajax page and then press back, then the code that was previously Ajax was all poured out, because the context has been switched, the browser does not know how to handle the code.

It's time to do two deals.

1) requires Ajax-related pages not to be cached, if you use Rails, you can read this article: http://blog.serendeputy.com/posts/ how-to-prevent-browsers-from-caching-a-page-in-rails/

2) The method of handling Popstate adds a flag bit, do not invoke the following logic when loading the page for the first time.

if (history && history.pushstate) {

var loaded = false;

$ (window). Bind ("Popstate", function () {if (!loaded) {

loaded = true;

} else {

$.getscript (LOCATION.HREF);

}

});

}

Notice the effect of this variable loaded. Because the page cache has been closed before, if you do not set this flag, the browser will be loaded in the back of the page, but also triggered the Popstate event, resulting in two load.

Second paragraph

History.pushstate/replacestate method

Familiar with the development of JavaScript, the history is certainly not unfamiliar, the most classic method is go, through the first type is an integer transmission parameters, you can make the browser to reach the current page before or after the page has been browsed. Of course, this is also to be refreshed to achieve.

Now the history API added two methods, namely Pushstate and replacestate, in fact, the use of the same, look at the Mozilla document also did not see how different they are, haha.

Use the following:

var state = {//This can be a state object that you want to give the browser, ready for the stateevent behind.

Title: "HTML 5 History API Simple Demo",

URL: "Yourpage"

};

History.pushstate (state, "the HTML 5 history API Simple Demo", "Yourpage");

It is simple, then replacestate is the same usage:

var state = {//This can be a state object that you want to give the browser, ready for the stateevent behind.

Title: "HTML 5 History API Simple Demo",

URL: "Yourpage"

};

History.replacestate (state, "the HTML 5 history API Simple Demo", "Yourpage");

State Event

Since there is no way to refresh the URL change, of course, also have to respond to this change of time.

Well, that's right. There is a Popstate event, and the incoming handler function has a parameter, which is the first parameter in the Pushstate, a state obj. Developers can use this state obj to identify behavior. The detailed code is as follows:

var state = {//This can be a state object that you want to give the browser, ready for the stateevent behind.

Title: "HTML 5 History API Simple Demo",

URL: "Yourpage"

};

History.pushstate (state, "the HTML 5 history API Simple Demo", "Yourpage");

Window.onpopstate = function (e) {document.title = E.state.title;}

Of course, you can do this:

var state = {//This can be a state object that you want to give the browser, ready for the stateevent behind.

Action: "Page",

Title: "HTML 5 History API Simple Demo",

URL: "Yourpage"

};

History.pushstate (state, "the HTML 5 history API Simple Demo", "Yourpage");

Window.onpopstate = function (e) {

Switch (e.state.action) {

Case "Home":

Document.title = "HOME ...";

$.get ("index.php"). Done (function (data) {

$ ("#wrapper"). HTML (data);

});

Break

Case "page":

Document.title = E.state.title;

$.get (E.state.url). Done (function (data) {

$ ("#wrapper"). HTML (data);

});

Break

}

}

Window.location.hash Property Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.