More Scripts Tips (1) - document-start

More Scripts Tips (1) - document-start

The More Scripts plugin supports running scripts when a web page starts loading (document start). While running scripts on document start (before the web page is visible) is always desirable, not all scripts can be run effectively on document start. Actually most scripts can only be run when web page is loaded (document complete).

This is because on document start, only the window and document object is available, and the <head> section is just loaded, the document body and other page elements are not yet created. A script cannot operate elements before they exist. For example to make all links to open in new tab, we could use the following script to set the target attribute of all links to '_blank'
Copy to clipboard
Code:
for(var j=0; j<document.links.length; j++){
        document.links[j].target = '_blank';
}
But since this script operates all links, which does not exist on document start, this script can only be run on document complete (the default option).

Yet with a different logic, the same result can be achieved at document start. Instead of changing all the links (non exist until web page is loaded), the script can change the link clicked (must already exist to be clicked).
Copy to clipboard
Code:
document.attachEvent('onmousedown', openLinkInNewTab);
function openLinkInNewTab(){
        var oElem=event.srcElement;
        while(oElem.tagName!='A' && oElem.parentElement){
                oElem=oElem.parentElement;
                if(oElem.tagName=='BODY') break;
        }
        if(oElem.tagName=='A') oElem.target='_blank';
}
Initially the script only attaches a function to the document's onmousedown event. This allows the script to be run on document start.

When a mouse down on the document is detected, the script checks if the element is a link. If not it checks if it has a parent element and if the parent is a link. This repeats until a link is found or the BODY element is reached. If a link is found, it set the link's target to "_blank". The reason for the parent looping is that the element clicked on may be a linked image or other element inside a link.

The second script looks a lot more complicated, does it has worse performance? On the contrary, it is more efficient in most cases.

The first script has to enumerate and process all the links whether the user open any link or not. It could take seconds on large pages. The second script only attach an event handler to the document regardless of the number of links. The core processing is deferred to when the document is clicked. And when that happens, the script process only one link instead of all, with a little extra looping to find the link. As long as the user isn't playing online shoot game, it's completely negligible.