Redirect Dynamic Anchor URLs
When you get in to dynamic content loading, you're presented with a couple problems:
- You want users to be able to copy a link to the particular page their on, and;
- Those anchored URLs can get rather long and ugly.
Since there is no way to detect anchors on the server side for redirect, all that can be done is to rely on Javascript. Fortunately, it isn't all that difficult.
if (window.location.hash && window.location.hash.charAt(1) == '/') {
window.location = window.location.hash.substring(1);
}
That little bit of code checks for a hash/anchor in the URL beginning with a forward slash, and redirects the browser to that URL. If put in the <head> of your document, then it will be triggered before and of the prior page is displayed to the visitor.
The check for a forward slash is to ensure standard named anchors on the page will work as intended, along with the added benefit of not redirecting to some other website in the case of a malicious 'http://' anchor. Note the charAt(1) and substring(1), which are used because '#' is at position 0 and needs to be trimmed.