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

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

问题描述

具体来说,我正在评估页面上的所有图片,看它们是否具有某个特定属性,然后添加一些新的< divs>基于这些属性到DOM。我必须等待document.ready在执行这些修改之前触发,以保证Chrome已经加载了DOM的所有必要部分吗?

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?

m遇到的情况是,有时document.ready需要一段时间才会触发,并且用户已经在浏览页面,想知道为什么我的扩展没有任何效果。这个问题通常只会持续一段时间,但它足以令人讨厌。

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.

如果我不打扰等待document.ready,而是立即处理文档, 似乎起作用;但我不知道我是否幸运。

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.

推荐答案

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

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.

document_end 中,文件在DOM完成后立即注入,但在加载像子图像和框架之类的子资源之前。 document_idle (默认值)甚至稍后发生。

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天全站免登陆