我收到一条警告消息:
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 警告和 <script>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28322636/