简体   繁体   中英

Javascript try catch statement

I'm analyzing some code on a website and I came across the following anonymous function followed by a try catch statement. I'm just wondering what the try catch statement is doing at the end there. Is it pre-loading the url so thats it loads more quickly then the anonymous function goes? Also, whats the point is it's not catching any errors.

(function() {
        var fired = false;
        bsnPop.add("http://www.someurl.com", {
            under: !noPopunder,
            newTab: false,
            forceUnder: true,
            shouldFire: function() {
                return !fired;
            },
            cookieExpires: -1,
            afterOpen: function(url) {
                createCookie();
                fired = true;
                doSecondPop();
            }
        });
    })();
    try {
        var hint = document.createElement("link");
        hint.rel = "dns-prefetch";
        hint.href = "http://www.someurl.com";
        document.head.appendChild(hint);
        var hint = document.createElement("link");
        hint.rel = "preconnect";
        hint.href = "http://www.someurl.com";
        document.head.appendChild(hint);
    } catch (e) {}

With reference to the link types list on MDN, "dns-prefetch" and "preconnect" are listed as experimental. They do not appear in the list of "rel" values for link types of link elements in HTML5

So the code is using experimental technology on the web which might throw an error in some browsers. To prevent stopping the application and logging an exception on the console, the code is placed in a try block with a catch block that ignores the error.


In answer to question details, the anonymous function in the IIFE is invoked and passes an object containing parameters and callbacks in a call to bsnPop.add . It does not appear to create a popup window at this stage.

Next code within the try block attempts to speed up access to the web site by requesting DNS lookup of the website's name in advance, and to open a connection to the site before attempting to retrieve content.

The code is placed in the try block to accommodate the possibility of a browser throwing an exception if the requested operations are not supported. The application does not consider lack of support an error and wants to continue anyway.

The end result is that if dns-prefetch or preconnect are supported the browser can take the hint and perform the operations. If they are not supported any error generated is ignored and code continues at the next statement - connecting to the website later will have to proceed at normal speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM