我正在从另一个 Web 服务动态加载一个小部件,该服务需要在其之后立即运行一个脚本。该示例使用 document.write() 来执行此操作,但这不起作用,因为它直到文档关闭后才运行,这意味着它会覆盖整个文档。我正在尝试使用纯 JavaScript 通过 AJAX 加载它:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // success
eval(this.responseText);
}
};
xhttp.open("GET", "https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js", true);
xhttp.setRequestHeader('Content-type', 'application/javascript');
xhttp.send();
但我收到以下错误:
XMLHttpRequest cannot load https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.
我能够使用 jQuery 在我的测试服务器上使用以下代码使其工作:
$.ajax({
dataType: "script",
cache: true,
url: "https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js"
});
但是,我无法在我的生产服务器上使用 jQuery,因为...好吧...工作政治。
jQuery 如何在没有错误的情况下完成此操作,以及如何在纯 JavaScript 中完成此操作?
解决方案
正如 @shabs 所说,$.ajax
将脚本标记添加到 document.head
中,然后立即将其删除。我通过添加断点进行了检查,并在 Chrome 的检查器中看到了它的添加和删除。无论文件是什么,它都会在当前脚本完成后立即删除该文件。这对于立即调用的脚本非常有效,但我不知道这如何与库之类的东西一起工作。
对于纯 JavaScript 实现,我使用了以下代码:
var widgetScript = document.createElement("script");
widgetScript.async = true;
widgetScript.src = "https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js";
document.head.append(widgetScript);
widgetScript.remove();
最佳答案
相关资源不支持CORS .
这通过 $.ajax
起作用。因为当您指定dataType: "script"
时,jQuery 实际上附加了一个 <script>
标记为document.head
! *
您不只是使用 <script type="text/javascript" src="https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js"></script>
之类的东西是否有特殊原因? ?
* (这对我来说是新闻! documentation for $.ajax
提到“脚本 [...] 请求不受同源策略限制”,并且 the source code 证实了这一点。)
关于javascript - 通过 AJAX 加载 JavaScript 文件而不使用 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45578711/