jquery - 同步 XMLHttpRequest 警告和 <script>

标签 jquery ajax

我收到一条警告消息:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.

当执行包含脚本(具有本地 src )的异步 AJAX 请求时,该脚本使用 $.html() 注入(inject)到 HTML 中方法。我已更改给定的脚本以包含 async="async" ,但警告消息仍然存在。

我已开始调试该问题,发现我附加的 <script>通过来自 jQuery.ajaxTransport 的 jquery AJAX 调用进行处理( http://code.jquery.com/jquery-1.10.0.js ,#8663),其中 async设置为false (这可能就是问题的根源)。

现在 - 我该怎么办?

该消息会出现在最新版本的 Chrome 和 Firefox 中。

<小时/>

虽然我无法提供 jsfiddle 上的测试用例,但这里有一个显示问题的测试用例:

测试.html

<html>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script>
$(document).ready(function(){
    $.ajax({
        url: '/response.html',
        success: function(response){
            $(document.body).html(response);
        }
    })
});
</script>
</body>
</html>

响应.html

<script type="text/javascript" src="/json.js" async="async"></script>

json.js

console.log('hi');
<小时/>

AJAX 请求不需要触发警告 - 只需插入 <script>

test2.html

<html>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script>
$(document).ready(function(){
    $(document.body).html('<script type="text/javascript" src="/json.js" async="async"><\/script>');
});
</script>
</body>
</html>
<小时/>

值得注意的是,根据https://github.com/jquery/jquery/issues/2060,此问题已得到修复。

最佳答案

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.

您可以修复它,将 xhr 请求的异步选项显式设置为 true:

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

关于jquery - 同步 XMLHttpRequest 警告和 &lt;script&gt;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28322636/

相关文章:

javascript - ajax内容应用到元素后执行js函数

javascript - 根上的 Spring RequestMapping

javascript - 根据相机 View 变化计算对象旋转

jquery - Cordova Ios 应用程序在相机访问时崩溃

javascript - 当用户滚动到网站部分时淡入 div

javascript - 如何根据服务器响应而不是 HTTP 500 触发 jquery.ajax() 错误回调?

php - AJAX 提交的结果未显示

javascript - iOS 6 上的 Safari 是否缓存 $.ajax 结果?

javascript - 使用 JavaScript 从 XML 文件搜索并输出数据

javascript - 使用 AJAX 将 JSON 对象发送到服务器