Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  153] [ 7]  / answers: 1 / hits: 43002  / 12 Years ago, sun, january 27, 2013, 12:00:00

In earlier versions, I used to test if I should be triggering popstate manually on page load, because Chrome triggers it right after load, and Firefox and IE do not.



if ($.browser.mozilla || $.browser.msie) {
$(window).trigger('popstate');
}


Now that they dropped the browser object in 1.9, how should I test for these browsers? Or how do I figure if I need to popstate on page load or not?



The code is:



$(function(){
$(window).on('popstate', popState);

// manual trigger loads template by URL in FF/IE.
if ($.browser.mozilla || $.browser.msie) {
$(window).trigger('popstate');
}
});


Update



Went for this:



    function popState(e){
var initial = e.originalEvent === undefined || e.originalEvent.state === null;
if(!initial){
activateRoute({
key: e.originalEvent.state.key,
settings: e.originalEvent.state.settings
},'replace');
}
}

function init(){
$(window).on('popstate', popState);

$(function(){
var route = getRoute(document.location.pathname);
activateRoute(route, 'replace');
});
}

More From » jquery

 Answers
15

You should add a little sanity check to your popstate handler, and make sure that it doesn't do anything expensive if you pop into the same state you started in. Then you can not care about the browser, and instead just call your popstate on document ready:



$(function(){
$(window).on('popstate', popState);

// call popstate on document ready
$(popstate);
});


The answer suggesting you paste the code from $.browser back into your environment is way overkill to support a bad practice. You can feature detect 99% of the things you need to. Almost every use of $.browser is a dangerous. There are almost always ways to detect that.



The JavaScript community has been against browser sniffing for a long time. Here is a post from 2009 telling us why it's a bad idea. There are many others.



I beg you not to copy $.browser back into your code, the jQuery team decided to kill it for a reason.


[#80598] Friday, January 25, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briza

Total Points: 259
Total Questions: 94
Total Answers: 101

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
;