使用“// script [contains(@src,'blah')”查找异步脚本

时间:2022-12-06 10:40:28

So there are several posts on how to query the dom to find an element by xpath. I found a post, Is there a way to get element by XPath using JavaScript in Selenium WebDriver?, that mostly meets my needs. My problem is stemming from the fact that the element I am trying to locate is a script, and that script needs to be loaded asynchronously. That seems to break finding its path using

因此,有几篇关于如何查询dom以通过xpath查找元素的帖子。我发现了一篇帖子,有没有办法通过在Selenium WebDriver中使用JavaScript获取XPath元素,这大多满足了我的需求。我的问题源于我试图找到的元素是一个脚本,并且该脚本需要异步加载。这似乎打破了使用它的路径

var path = "//script[contains (@src, 'locationOfScript')]";

I think the root cause may be Chrome delaying the async script load until after the page is complete: Chrome delays load of script with async attribute.

我认为根本原因可能是Chrome推迟异步脚本加载直到页面完成后:Chrome会延迟使用async属性加载脚本。

I'm developing a userscript in Chrome, and must leave the script as async, otherwise I'd just drop the async attribute.

我正在Chrome中开发用户脚本,并且必须将脚本保留为异步,否则我只需删除异步属性。

Any way to query the document for a script that won't load until after everything else?

有什么方法可以查询文档中的脚本,直到其他所有内容之后才会加载?

Thanks!

1 个解决方案

#1


The async attribute will cause the script not to block so you cannot be sure when it will load. However, you can be sure when the DOM is done being loaded with the following code:

async属性将导致脚本不会阻塞,因此您无法确定何时加载。但是,您可以确定何时使用以下代码加载DOM:

document.onreadystatechange = function () {
    if (document.readyState === "complete") {
        var path = "//script[@src='locationOfScript']";
        // etc...
    }
}

#1


The async attribute will cause the script not to block so you cannot be sure when it will load. However, you can be sure when the DOM is done being loaded with the following code:

async属性将导致脚本不会阻塞,因此您无法确定何时加载。但是,您可以确定何时使用以下代码加载DOM:

document.onreadystatechange = function () {
    if (document.readyState === "complete") {
        var path = "//script[@src='locationOfScript']";
        // etc...
    }
}