gpt4 book ai didi

javascript - 如何阻止外部JS请求

转载 作者:行者123 更新时间:2023-12-02 22:58:44 25 4
gpt4 key购买 nike

我正在使用自动构建和托管启动页面的服务。在他们的代码正文中,他们调用了 jquery:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js?cache=2015-09-22-09">

不幸的是,由于我在中国,googleapis.com 被阻止,页面必须等待此代码超时才能呈现。这部分是作为模板的一部分自动生成的,我无法更改它。不过我可以在头部和主体中插入自定义 JavaScript。

有什么方法可以阻止此代码向 googleapis.com 发出请求或在发出请求后强制其中止?

-编辑-

这是我尝试加载页面时网络选项卡的屏幕截图。正如您所看到的,对 googleapis.com 的调用挂起 1.4 分钟,直到超时,此时 DomContentLoaded 会触发并加载整个页面。

enter image description here

最佳答案

对,如果您能够将 html 放在文档的头部,而不仅仅是执行 javascript,您可以使用元标记来阻止外部脚本加载:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">

来自Mozilla Content-Security-Policy Meta Tag Docs :

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which preceds them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which precede a meta-delivered policy will not be blocked.

所以元标记只能在头部工作,当然是在加载 jQuery 的脚本之前。您也可以将标记中的 URL 添加到元标记的内容参数中,从而将其列入白名单。

如果只能执行javascript,可以动态添加meta标签。不幸的是,浏览器很可能在添加它时就已经决定了它的策略。不过,可以添加

var meta = document.createElement('meta');
meta.httpEquiv = "Content-Security-Policy";
meta.content = "script-src 'self'";
document.getElementsByTagName('head')[0].appendChild(meta);

更多有趣的阅读 Material 作业,用于解决“防止外部 js 请求”之谜:

Use JavaScript to prevent a later `<script>` tag from being evaluated?

祝你好运!

关于javascript - 如何阻止外部JS请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com