什么是同步 XMLHttpRequest? [英] What is Synchronous XMLHttpRequest?

查看:33
本文介绍了什么是同步 XMLHttpRequest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试,看看我是否可以在文档准备好后使用 javascript 加载 .js,并从 chrome 收到此警告消息:

I was testing and see if I can use javascript to load .js after the document is ready, and got this warning message from chrome:

主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响."

"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience."

我的代码如下:

$(document).ready(function(){
    var s=$('<script src="test.js"></script>');
    $('body').append(s);
});

我的问题是:

1) 在这种情况下,什么是同步 XMLHttpRequest"?我认为这与'test.js'的加载有关,但是如果我将其更改为 var s=$('<img src="image.png"></img>'); 警告信息不会显示.

1) In this case, what is considered a "Synchronous XMLHttpRequest"? I think it is related to the loading of 'test.js', but if I change it to var s=$('<img src="image.png"></img>'); the warning message won't show.

2) 如果 .js 文件必须以这种方式加载,最佳做法是什么?

2) If the .js file has to be loaded this way, what is the best practice?

*********** 编辑***********

*********** Editting ***********

test.js 的内容是

The content of test.js is

console.log(document.getElementsByTagName('h1'))

HTML 中有一个 h1.

There is a h1 in HTML.

推荐答案

我相信您的问题与 async

在 HTML5 中:asyncdefer,您可以告诉浏览器何时运行您的 JavaScript 代码.有3种可能:

In HTML5: async, defer, you can tell browser when to run your JavaScript code. There are 3 possibilities:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>

  1. 如果没有 asyncdefer,浏览器会立即运行你的脚本,在呈现脚本标记下方的元素之前.
  2. 使用 async(异步),浏览器将继续加载 HTML页面并在浏览器加载和执行脚本时呈现它同时.
  3. 使用defer,浏览器会在页面完成时运行你的脚本解析.(不需要下载完所有的图像文件.这个很好.)
  1. Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.
  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.
  3. With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)

我发现以下答案:synchronous-xmlhttprequest-on-the-不推荐使用主线程

使用 jQuery 将脚本标签附加到文档将导致它使用 async:false 加载脚本并触发此警告.

Using jQuery to append a script tag to the document will cause it to load the script with async:false and trigger this warning.

var script = $("<script></script>");
script.attr("src", player.basepath + "whatever.js");
$(document.body).append(script);

未测试.仅供参考.

这篇关于什么是同步 XMLHttpRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆