0%

javascript-url-fragment

Introduction

URL fragment is the part of the URL that comes after the # symbol.

url

1. A fragment in a url specify the location within the page.

How to go to the specific location in the page?

  1. Create a empty <a> tag with id attribute set to the fragment part in url.
1
2
3
4
5
6
<a id="fragment1">
content of fragment 1
</a>
<a id="fragment2">
content of fragment 2
</a>

input the following url in your browser http://example.com/page.html#fragment1, the browser will scroll to the location of the fragment1 in the page.

If you want to jump to the specific location in the page by clicking a link in the page, you can create a link with its href set to the id part of the section.

1
2
<a href="#fragment1">Go to fragment 1</a>
<a href="#fragment2">Go to fragment 2</a>

2. Fragment never send to server in http request.

The fragment part of the URL is never sent to the server. It is only used by the browser. Take the following URL as an example, when you input it in the browser, observe the network tab in the developer tools, you will find that the fragment part is not sent to the server. the server only receives the request for the URL http://example.com/page.html.

1
https://localhost:3000/page1#fragment

3. Anything after the first # is a fragment identifier.

The url below want to set the color by the fragment part of the URL, but it won’t work because browser will parse the fragment part as #ffff&shape=circle instead of #ffff.

1
http://example.com/?color=#ffff&shape=circle

4. Changing fragment id doesn’t reload a page but create history.

When you change the fragment part of the URL, the page will not reload, but it will create a new entry in the browser history. You can use the forward and back button in the browser to navigate between the history entries.

## 5. Googlebot ignores the fragment part of the URL.

# References:
1. https://blog.httpwatch.com/2011/03/01/6-things-you-should-know-about-fragment-urls/
2. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web#Fragment