Userscript在执行代码技术之前等待页面加载?

我正在写一个Greasemonkey用户脚本,并希望在页面完全加载时执行特定代码,因为它返回我想要显示的div计数。

问题是,这个特定的页面有时会在所有内容加载之前占用一些。

我试过,记录$(function() { });$(window).load(function(){ }); 包装。 但是,似乎没有一个对我有用,尽管我可能会错误地应用它们。

我能做的最好是使用setTimeout(function() { }, 600); 哪个有效,但并不总是可靠的。

什么是在Greasemonkey中使用的最佳技术,以确保在页面加载完成后执行特定代码?

Greasemonkey(通常)没有jQuery。 所以常见的方法是使用

 window.addEventListener('load', function() { // your code here }, false); 

在你的用户名内

这是一个常见问题,正如您所说,等待页面加载是不够的 – 因为AJAX可以并且确实在此之后很久就会改变。

对于这些情况,存在标准(ish)稳健实用程序。 这是waitForKeyElements()实用程序 。

像这样使用它:

 // ==UserScript== // @name _Wait for delayed or AJAX page load // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== /*- The @grant directive is needed to work around a major design change introduced in GM 1.0. It restores the sandbox. */ waitForKeyElements ("YOUR_jQUERY_SELECTOR", actionFunction); function actionFunction (jNode) { //-- DO WHAT YOU WANT TO THE TARGETED ELEMENTS HERE. jNode.css ("background", "yellow"); // example } 

提供目标页面的确切详细信息以获取更具体的示例。

从Greasemonkey 3。6(2015年11月20日)开始,元数据键@run-at支持新值document-idle 。 只需将它放在Greasemonkey脚本的元数据块中:

 // @run-at document-idle 

文档描述如下:

该脚本将在页面之后运行,并且所有资源(图像,样式表等)都已加载并且页面脚本已运行。

$(window).load(function(){ })包装我的脚本对我来说永远不会失败。

也许你的页面已经完成,但仍然有一些ajax内容被加载。

如果是这样的话, Brock Adams的这段精彩代码可以帮助您:
https://gist.github.com/raw/2625891/waitForKeyElements.js

我通常用它来监视回发时出现的元素。

像这样使用它: waitForKeyElements("elementtowaitfor", functiontocall)

如果要操作节点(如获取节点值或更改样式),可以使用此函数等待这些节点

 const waitFor = (...selectors) => new Promise(resolve => { const delay = 500 const f = () => { const elements = selectors.map(selector => document.querySelector(selector)) if (elements.every(element => element != null)) { resolve(elements) } else { setTimeout(f, delay) } } f() }) 

然后使用promise.then

 // scripts don't manipulate nodes waitFor('video', 'div.sbg', 'div.bbg').then(([video, loading, videoPanel])=>{ console.log(video, loading, videoPanel) // scripts may manipulate these nodes }) 

或使用async&await

 //this semicolon is needed if none at end of previous line ;(async () => { // scripts don't manipulate nodes const [video, loading, videoPanel] = await waitFor('video','div.sbg','div.bbg') console.log(video, loading, video) // scripts may manipulate these nodes })() 

以下是icourse163_enhance的示例

Brock的答案很好,但我想为AJAX问题提供另一种解决方案,以确保完整性。 由于他的脚本也使用setInterval()定期检查(300ms),因此无法立即响应。

如果需要立即响应,可以使用MutationObserver()监听DOM更改并在创建元素后立即响应它们

 (new MutationObserver(check)).observe(document, {childList: true, subtree: true}); function check(changes, observer) { if(document.querySelector('#mySelector')) { observer.disconnect(); // code } } 

虽然check()会触发每个DOM更改,但如果DOM经常更改或者您的条件需要很长时间来评估,这可能会很慢。

另一个用例是,如果您没有查找任何特定元素,只是等待页面停止更改。 您可以将它与setTimeout()结合使用以等待它。

 var observer = new MutationObserver(resetTimer); var timer = setTimeout(action, 3000, observer); // wait for the page to stay still for 3 seconds observer.observe(document, {childList: true, subtree: true}); function resetTimer(changes, observer) { clearTimeout(timer); timer = setTimeout(action, 3000, observer); } function action(o) { o.disconnect(); // code } 

此方法非常通用,您也可以监听属性和文本更改。 只需在选项中将attributescharacterData设置为true

 observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true}); 

为了检测XHR是否在网页中完成加载,它会触发一些function。 我从中如何使用JavaScript在Chrome控制台中存储“XHR已完成加载”消息? 它真实有效。

  //This overwrites every XHR object's open method with a new function that adds load and error listeners to the XHR request. When the request completes or errors out, the functions have access to the method and url variables that were used with the open method. //You can do something more useful with method and url than simply passing them into console.log if you wish. //https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { this.addEventListener('load', function() { console.log('XHR finished loading', method, url); display(); }); this.addEventListener('error', function() { console.log('XHR errored out', method, url); }); origOpen.apply(this, arguments); }; })(); function display(){ //codes to do something; } 

但如果页面中有很多XHR,我不知道如何过滤明确的XHR。

另一种方法是waitForKeyElements(),这很好。 https://gist.github.com/BrockA/2625891
有Greasemonkey使用的样本。 多次在同一页面上运行Greasemonkey脚本?