javascript - 通过 AJAX 加载 JavaScript 文件而不使用 jQuery

标签 javascript ajax

我正在从另一个 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/

相关文章:

JQuery 冲突 Ajax 验证消息返回位置

javascript - 使 HTML 页面与 C 中的套接字通信

php - 当包含特定文件扩展名时如何将类添加到超链接?

javascript - 配置我的代码附加到子级而不是innerHTML

ajax - f :ajax in ui:repeat renders h:outputText but fails to render/update h:inputText

javascript - 使用 JSON 从 Ajax 调用获取未定义的数组类型

javascript - jQuery $.when() 和 ajax 调用

javascript - 将对象移向javascript中的一个点

javascript - 如何选择数据列表的描述

javascript - 在 ajax json 脚本中添加基本的 http 授权