Update window.location.hash in Chrome?

I searched the Internet and found that window.location.hash = "etc" is a widespread method for updating the location of the browser without reloading / refreshing the page. I applied this to this example that I prepared: http://dl.dropbox.com/u/1595444/locationExample/index.html

Works well in Safari, but ...

I noticed that in Chrome 10+ when changing hash :

There is something like a reboot. The resulting symptom is a hiccup when the user scrolls up or down. My console output is saved (if you check your console, the project line is displayed). Favicon is supposed to reboot.

Has anyone encountered this problem before? Know the fix?

+6
source share
3 answers

There are likely two things here:

  • The favicon and stop / refre buttons flicker due to a Chrome bug (which mentions pushState , but hash changes in the same code path).
  • A little hiccup when scrolling is that Chrome does a complete redraw of the page and a high-quality scale for updating page thumbnails, as it considers hash changes to generate a new URL. This is also a mistake . You can see this in the inspectorโ€™s timeline view, most scroll events result in redrawing the window width x of some small height, but sometimes the full window is repainted. This blog post has some details.

A workaround for both would be to delay updating the hash until the user scrolls (you can update the white bar that appears immediately below the current item). You can do this by having something like:

 var scrollTimeout; window.onscroll = function() { // update current item display here if (scrollTimeout) clearTimeout(scrollTimeout); scrollTimeout = setTimeout(function() { scrolTimeout = undefined; // update hash here }, 100); }; 

Since it looks like you are using jQuery, there are debouncing plugins that can be useful.

+6
source

I do not have a definitive answer, but first I will try:

  • Turn a hash tag (#) into a value (i.e. use window.location.hash = "#etc").
  • Register a handler for the window.onhashchange handler.
  • Alternatively, you can use history.pushState if what you are trying to do is return the return button to the previous logical location (itโ€™s not clear to me what you are trying to do, if you just want to go to the section on the page or something more complicated).
+1
source
 var r='#hello'; if(navigator.userAgent.indexOf('Chrome/')!=-1){ top.history.pushState("", "", r); return; }; if(r.charAt(0)=='/'){ top.location.replace(r); }else{ top.location.hash=r; }; 

Worked for me. And it took me a long time to figure it out. Firefox now also supports the history object, so we can get rid of the whole "hash thing" in a few years.

EDIT: Yes, rebooting is a Chrome bug.

+1
source

Source: https://habr.com/ru/post/885873/


All Articles