问题
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?
回答1:
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==
回答2:
This call may be being loaded too late on the page. Add this code to the very top of the page and see if that fixes it.
If that isn't it please post some additional information. (Where the call is being made? Some more information on the page? Is this being called from an external .js file?)
来源:https://stackoverflow.com/questions/9825754/window-load-doesnt-fire-always-on-chrome