Search code examples
javascriptgoogle-chromegreasemonkeyonloaduserscripts

window.load doesn't fire always on chrome?


I have this userscript:

// ==UserScript==
// @name          test
// @namespace     test
// @description   show's an alert on load
// @include       http://*
// @include       https://*
// ==/UserScript==

window.addEventListener('load', function(){alert("loaded");}, false);

This works fine on Firefox on all pages but doesn't work at all on Chrome at some occasions.

One example is this website: http://lexin.nada.kth.se/lexin/ Entering the link in the address and hitting enter, loads the page normally but no alert is popped up. If you press F5 to refresh the page, the popup appears.

Is there some explanation to this weird behaviour?


Solution

  • The cause of the problem is that the Content script is sometimes executed when the document has already fully loaded. This is illustrated using the following Content script ("User Script"):

    // ==UserScript==
    // @name          Test
    // @namespace     Test
    // @include       *
    // ==/UserScript==
    
    window.addEventListener('load', function(){alert("loaded");}, false);
    alert(document.readyState);   // When this prints "complete", onload never runs
    

    To solve the issue, use the @run-at document-start meta-rule, which causes the script to execute before the document is created:

    ...
    // @run-at   document-start
    // ==/UserScript==