在 Chrome 扩展内容脚本中,我是否必须在处理文档之前等待 document.ready? [英] In a Chrome Extension content script, must I wait for document.ready before processing the document?

查看:34
本文介绍了在 Chrome 扩展内容脚本中,我是否必须在处理文档之前等待 document.ready?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我正在评估页面上的所有图像以查看它们是否具有特定属性,然后添加一些新的

到基于这些属性的 DOM.在执行这些修改之前,我是否必须等待 document.ready 触发才能确保 Chrome 已加载所有必需的 DOM 部分?

我遇到的问题是有时 document.ready 需要很短的时间才能触发,而用户已经在浏览页面,想知道为什么我的扩展程序还没有任何效果.问题通常只持续片刻,但足以令人讨厌.

如果我不费心等待 document.ready,而是立即处理文档,一切似乎都可以工作;但我想知道我是否只是走运了.

解决方案

实际上,您不必等待.您可以立即在内容脚本中进行处理.只需确保不要在 run_at 属性中使用 document_start.

document_end 中,文件在 DOM 完成后立即注入,但在图像和框架等子资源加载之前.document_idle(默认值)发生得更晚.

<代码>{"name": "我的分机",...内容脚本":[{"匹配": ["http://www.google.com/*"],"css": ["mystyles.css"],"js": ["jquery.js", "myscript.js"],"run_at": "document_end"}],...}

Specifically, I'm evaluating all of the images on a page to see if they have a certain attribute, and then adding some new <divs> to the DOM based on those attributes. Must I wait for document.ready to fire before performing these modifications in order to be guaranteed that Chrome has loaded all of the necessary pieces of the DOM?

The problem I'm running into is that sometimes document.ready takes a short while to fire and the user is already browsing around the page, wondering why my extension hasn't yet had any effect. The problem usually only lasts a moment, but it's enough to be annoying.

If I don't bother waiting for document.ready, and instead immediately process the document, everything seems to work; but I wonder if I'm just getting lucky.

解决方案

Actually, you don't have to wait. You can process right away in Content Scripts. Just make sure you don't use document_start in the run_at attribute.

In document_end, the files are injected immediately after the DOM is complete, but before subresources like images and frames have loaded. document_idle (the default value) happens even later.

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"],
      "run_at": "document_end"
    }
  ],
  ...
}

这篇关于在 Chrome 扩展内容脚本中,我是否必须在处理文档之前等待 document.ready?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆