欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

defer与async的认识

发布时间:2024/9/20 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 defer与async的认识 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

defer跟asyns都是脚本外联文件的标签属性(标签内的脚本不会执行),加了这两个属性其中一个那么脚本文件会异步加载执行。

首先检查defer在浏览器中执行顺序(检查浏览器为chome,firfox,ie)

defer:

在编译器中输入代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>defer async</title>
<style>
</style>
<script type="text/javascript">
  console.log("head内嵌js")
</script>
</head>
<body>
  <img src="../images/1.jpg" alt="1.jpg" οnlοad="console.log('img')" />
  <script type="text/javascript" src="js/defer.js" defer="defer"></script>
  <script type="text/javascript">

    window.onload = function(){

      console.log("onload")
    }

    console.log("内嵌js")
  </script>
</body>
</html>

在chome,firfox的控制台中,输出先后顺序为

head内嵌js
内嵌js this is defer img onload 在ie的控制台中,输出先后顺序为

head内嵌js
img
内嵌js
this is defer

onload

defer要等到dom构造好了后再执行,所以'this is defer'会最后输出(上一篇文章对ie dom构造的理解是,dom中的所有资源下载后才能算构造好dom,不知道对不对?) 注:ie10中'内嵌js'先于'img'; 从浏览器的输出结果可以看出,加defer的外联标签加载的文件,会在dom树构成后执行,onload是在dom树构成后并且所有资源(包括图片css,js)加载到浏览器后再执行。但会在document的DOMContentLoaded事件之前。
在w3c上看到,支持defer的浏览器有:

Browser Support

    

The defer attribute is supported in all major browsers.

Note: The defer attribute is not supported in Opera 12 and earlier versions. async: 这个属性跟defer一样,异步下载资源,不会堵塞浏览器渲染页面,然而这个属性跟defer不同的是,当该文件加载完后会立即执行该外联文件里面的脚本,不用等到dom树构造好。同时,几个加async的脚本下载后,按照先到先执行的顺序,不会按代码中的排列顺序执行,这点跟defer不一样.

Browser Support

    

The async attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari.

Note: The async attribute of the <script> tag is not supported in Internet Explorer 9 and earlier versions.

转载于:https://www.cnblogs.com/outside/p/3723722.html

总结

以上是生活随笔为你收集整理的defer与async的认识的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。