More Resource Intensive: Tampermonkey script (for video control) running on ALL domains—or just 1K domains each with its own @include entry?

时间:2019-03-17 22:23:12

标签: greasemonkey userscripts tampermonkey

I've got a quick question--and I apologize in advance if the answer is (or should be) obvious… the question might betray my very basic [i.e., basically non-existent] fluency in code.

But I wrote a .js userscript in Tampermonkey to allow me to have more precise control over video playback in Safari. I've had it set to run on all domains:

// @include http://*
// @include https://*  

And while that's certainly worked for me thus far, I'm aware that the script runs needlessly on the 80% of my Internet-ing I do that doesn't involve any interaction with video elements… So I went through and compiled an exhaustive list of ~1,000 specific domains where it makes sense to have the script running, e.g.,:

// @include     *://*.facebook.com/*
// @include     *://*.vimeo.com/*
// @include     *://*.youtube.com/*

But after actually entering in 1,000 lines of this into my [formerly quite petite!] userscript, it dawned one me that--as far as I know--I could actually be greatly increasing the amount of system resources it takes to run this script by forcing it to now run through a long list of domains to see if it matches… and that perhaps simply having it run by default could be less resource-intensive?

Ha, at the same time, I can also imagine how running it everywhere = obviously more of a waste of resources… But since I've no idea how I'd even go about testing this (and I certainly don't have a solid enough grasp of the underlying theory here) --> I thought I'd leave it up to the experts, and reach out to you here for advice!

Thank you for your help!! :-)

1 个答案:

答案 0 :(得分:3)

部分答案,因为它太大了,无法发表评论,并且因为我现在不愿意设置和运行一些新实验。 (如果有人发布带有更新且可验证的数字的答案,我将对此表示赞赏。)

这是当您拥有Tampermonkey,Violentmonkey等并安装了用户脚本时发生的情况的粗略概图:

  1. 您访问的每个页面都会根据每个活动用户脚本@include@match@exclude指令进行检查>。精明的引擎会首先检查@exclude并在找到匹配项时停止。

    某些引擎比其他引擎更擅长此检查,并且理想情况下,站点匹配信息将保留在内存中以实现最大速度。

  2. 您访问的所有页面上的每个<frame>或iframe都根据@include@match@exclude指令进行检查,除非该脚本已设置@noframes

  3. 如果脚本与页面(或框架)匹配,则Tampermonkey(等)必须:
    (A)提取脚本代码以及所有数据-通常是从磁盘上获取(缓慢)。
    (B)然后创建某种级别的沙箱-取决于引擎,浏览器和@grant模式。
    (C)将脚本注入到上述沙箱中-几乎总是由匿名函数包装-并运行它。

  4. 然后,用户脚本将使用资源,具体取决于其代码。

通常:

  1. @match@include表现更好(最近一次检查)。如果要使用1000行,请在include上使用@match

  2. 使用@noframes,除非您有理由不这样做。

  3. 理想情况下,
  4. 步骤1和2可以全部从内存完成(需要查看各种引擎当前的工作),并且@include lot 可以同时处理需要注入一个用户脚本。 (有人想收集一些数字吗?)
  5. 如果需要从磁盘中获取用户脚本或其数据(@require文件,@resource文件,GM_setValue数据),则这是一个相当大的时滞。 (但仍然比从互联网上获取东西要快。)

最后,必须与脚本的侵入性相比,必须维护大量站点,每次编辑用户脚本文件所花费的时间和精力。 strong>。

如果是我,并且脚本只将页面延迟不到300毫秒,那么我会hold之以鼻并使用:

// @match    *://*/*
// @noframes

但是,如果脚本更具侵入性,更慢或更耗费资源,则可以使用混合方法...
将要完全运行的网站列表保留在GM_setValue数据和/或@resource d文件中。

这样,您可以使用菜单命令即时编辑列表。或通过Tampermonkey脚本数据编辑器;甚至通过为此目的创建的按钮。但是,所有这些都不在这个问题的范围之内。