如何阻止浏览器预加载< video>标签? [英] How do I prevent the browser from preloading the <video> tag?
问题描述
我已经使用JavaScript为Chrome编写了一个用户脚本扩展程序,以防止视频和音频代码在页面加载时自动下载。
I have written a user script extension for Chrome with JavaScript in order to prevent video and audio tags from downloading automatically on pageload
这是代码:
var videoTags = document.getElementsByTagName("Video");
var i;
for(i=0; i<videoTags.length; i++)
{
videoTags[i].setAttribute("preload", "none");
videoTags[i].removeAttribute("autoplay");
}
var audioTags = document.getElementsByTagName("audio");
var i;
for(i=0; i<audioTags.length; i++)
{
audioTags[i].setAttribute("preload", "none");
audioTags[i].removeAttribute("autoplay");
}
这是manifest.json文件:
And this is the manifest.json file:
{
"content_scripts": [ {
"exclude_globs": [ ],
"exclude_matches": [ ],
"include_globs": [ "*" ],
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
} ],
"converted_from_user_script": true,
"description": "",
"key": "an2xaeZJluPfnpmcsHPXI4aajQPL1cBm5C2kKjaQwXA=",
"name": "test.user.js",
"version": "1.0"
}
问题是我的脚本片刻后运行,直到那时浏览器(Chrome)才会下载部分视频/音频文件。
The problem is that my script runs after a moment and until then the browser (Chrome) downloads a part of video/audio file.
推荐答案
一个似乎有用的肮脏解决方案是使用 MutationObserver
用户脚本,一旦你确定它确实在document-start上运行。
One dirty solution that seems to work is to use a MutationObserver
from your userscript, once you're sure it does run at document-start.
这个TamperMonkey脚本对我有用:
This TamperMonkey script does work for me :
// ==UserScript==
// @name Block videos preloading
// @include *
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var nodes = mutation.addedNodes;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "VIDEO") {
nodes[i].setAttribute('preload', 'none');
nodes[i].removeAttribute('autoplay');
}
}
})
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
})();
您可能想要致电 observer.disconnect()
on DOMContentLoaded
,如果您不希望其他视频元素随后被脚本插入。
You may want to call observer.disconnect()
on DOMContentLoaded
, if you're not expecting other video elements for being inserted afterwards by scripts.
这篇关于如何阻止浏览器预加载< video>标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!