2

例如,google+ 给出了以下代码:

<!-- Place this tag after the last +1 button tag. -->
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>

但为什么不只是这样:

<script async src="https://apis.google.com/js/plusone.js"></script>
4

2 回答 2

3

asyncdefer并非所有浏览器都支持它的表亲。(例如,IE 直到 IE10 才获得它们。)第一种方法将始终是异步的,第二种方法不会在不支持async.

第一个总是异步的原因是script动态添加到 DOM 的元素不会阻止文档的解析和呈现,而<script>HTML 内容中的内联标签(除非使用 - 和支持 - asyncor defer) .

于 2013-03-12T11:39:25.263 回答
0

有很好的解释:哪些浏览器支持<script async="async" />?

是的,现在大多数浏览器都支持异步,但通常你需要 100% 保证你的代码可以工作,然后你需要使用第一种形式

于 2013-03-12T11:42:15.127 回答