Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

javascript - jQuery 1.9 browser detection

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');
        });
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...