我有这个:
script.js
:
function addStyleString(str) {
var node = document.createElement('style');
node.innerHTML = str;
document.body.appendChild(node);
}
var test = 'html {'
test += ' background-image: url("http://i.imgur.com/eWtfMME.png");'
test += ' background-repeat: repeat;'
test += '}'
addStyleString(test);
和manifest.json
:
{
"name": "test",
"description": "testtt",
"manifest_version": 2,
"version": "3.0",
"content_scripts": [
{
"matches": ["http://mywebsite.com"],
"js": ["script.js"]
}
]
}
它工作正常,但它会在网页加载后立即注入(inject)所有内容。我怎样才能使效果即时?就像 Stylish webextension
最佳答案
使用run_at
document_start
有多种方法可以做到这一点。假设您想继续使用 manifest.json content_script
进入,要做的就是拥有你的content_script
输入为 run_at
( MDN ) document_start
:
"content_scripts": [
{
"matches": ["http://mywebsite.com/*"],
"js": ["script.js"],
"run_at": "document_start"
}
]
如果您的 JavaScript 在 document_start
运行,您需要附加 <style>
到 document.documentElement
, 作为 head
和 body
那时还不存在。
注意:您的匹配模式有误,导致扩展程序无法加载。匹配模式必须指定一个路径。我添加了 /*
给你的matches
.
对于静态样式,使用 css
入口
但是,如果您只是添加静态 CSS,最好将 CSS 移动到一个单独的 .css 文件中,并通过 content_scripts
自动加载它。 css
( MDN ) 条目:
list .json:
"content_scripts": [
{
"matches": ["http://mywebsite.com/*"],
"js": ["script.js"],
"css": ["myStaticStyles.css"],
"run_at": "document_start"
}
]
myStaticStyles.css:
html {
background-image: url("http://i.imgur.com/eWtfMME.png");
background-repeat: repeat;
/*Added background-color because your image is dark. This helps there not be as much
of a flash of the normal white new-tab background while waiting for your image to
display. */
background-color: black;
}
网络请求的异步特性
特别是因为您使用的是 background-image
对于网络 URL,在将 CSS 插入 DOM 和显示图像之间存在延迟。这是因为 Chrome 识别需要获取 URL 和数据可用之间存在延迟。您可以通过使用不太复杂的图像来缩短它,将图像重新编码为更小,或者 converting the image to a data URL ,正如 wOxxOm 在评论中所建议的那样。
如果您的问题是有一个 background-image
在您试图覆盖哪些加载速度比您的图片快的网站中,您可以做一些可能的事情来阻止它加载:
- 修改页面的 HTML 以暂时删除使用不同的
background-image
加载其他 CSS 的元素。 .加载图像后,您可以重新插入元素。您可能需要使用webRequest
监听器来确定您的图像何时完成加载。一旦有,您可以重新插入负责其他的元素background-image
. - 使用
webRequest.onBeforeRequest
监听器取消对其他背景图像 URL 的请求。根据确切你想做什么,你可能需要结合内容脚本和/或webNavigation
来使用东西。听众。 - 修改正在加载到页面中的 CSS 以消除其他
background-image
.根据 CSS 的应用方式,这可能既复杂又困难,但有可能实现。
关于javascript - 注入(inject)CSS时立竿见影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739555/