开发者

How can I use #-URLs in a single-page application?

开发者 https://www.devze.com 2023-04-12 19:49 出处:网络
This article makes a pretty convincing argument that because URLs are long-lived (they get bookmarked and passed around), they should be meaningful, and that using the hash for real routing (determini

This article makes a pretty convincing argument that because URLs are long-lived (they get bookmarked and passed around), they should be meaningful, and that using the hash for real routing (determining what data is shown on the page and/or the state of the application) is thus improper. When I try to actually do that in my single-page application, though, I run up against a problem: how do I render my links so that all browsers can use the application? As I see it, there are three options:

  1. all hrefs have a #/ prefix. This works great in HTML4 browsers. In HTML5 browsers, I can add a Sammy route that redirects to the hash-less version, which also works great. There might be a problem with browsers marking links as visited when they're not or not marking them visited when they are. The other problem is that it's... wrong. Anyone who shares a link by right-clicking it and selecting "Copy Link URL" will be sending a working but kludgy URL around.
  2. no hrefs have a #/ prefix. As far as I can tell, HTML4 browsers will have no way of intercepting these link c开发者_如何转开发licks, which means that every one will cause a page refresh. Though the application would probably still function, since I could use Sammy routes to rewrite the hashless versions to hashy ones on page load, the page loads would kill the performance of the single-page application.
  3. I dynamically determine whether to prefix with #/ or not. This means that all of my links have to have dynamic markup and dramatically complicates the application.


The hash value of a URL never caused and entire re-load of page. Not in HTML4 and before that. A hash value has always been an internal link, and therefore it can be used perfectly (take a look at twitter for example). Of course, when you refresh the page, you will reload the page. But that is obvious.

With JavaScript you can actually read this hash value (see also this question/answer: How can you check for a #hash in a URL using JavaScript?) using window.location.hash

Using a more recent browser, you can also detect a hash change, which is useful if users actually change the URL: On - window.location.hash - Change?

But when you, as the website, change the URL you don't need read this, you already know because you just changed it.

This way, using hashes, people can exchange the URLs, and you can actually read which URL they are requesting, and therefore it should work perfectly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号