简体   繁体   English

window.load不会始终在chrome上触发吗?

[英]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. 在所有页面上的Firefox上都可以正常工作,但在某些情况下在Chrome上根本无法使用。

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. 一个示例是该网站: http : //lexin.nada.kth.se/lexin/在地址中输入链接并按Enter,正常加载页面,但没有弹出警报。 If you press F5 to refresh the page, the popup appears. 如果按F5刷新页面,则会显示弹出窗口。

Is there some explanation to this weird behaviour? 这种奇怪的行为有什么解释吗?

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元规则,该规则使脚本在创建文档之前执行:

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

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?) (在哪里进行调用?页面上有更多信息?这是从外部.js文件调用吗?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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