当使用“延迟”时,是否有必要将脚本放在页面底部?属性? [英] Is it necessary to put scripts at the bottom of a page when using the "defer" attribute?

查看:107
本文介绍了当使用“延迟”时,是否有必要将脚本放在页面底部?属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是将脚本标记放在页面底部,因为在HTML / CSS和文本加载完成之后加载脚本是一种很好的做法。我刚刚发现了defer属性,它基本上做同样的事情,就是在获取和执行脚本之前等待页面完成加载。

I always put my script tags at the bottom of the page since it's good practice to load scripts after things like HTML/CSS and text has finished loading. I just found out about the defer attribute which basically does the same thing, that is it waits till the page has finished loading before fetching and executing scripts.

所以如果使用延迟属性是否有必要将脚本标签物理地放置在页面底部和头部标签内?

So if using the defer attribute is it necessary to physically place script tags at the bottom of the page vs inside the head tag?

我发现将脚本标签保持在头部内部的可读性更好部分。

I find it better for readability to keep script tags inside the head section.

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

<script defer="defer">

// do something

</script>


推荐答案

你问的最佳做法是什么? 使用延迟脚本

The best practice you ask? Use deferred scripts

为什么?放在页面底部的脚本可以很好地工作,因为脚本通常会阻止并行下载,如HTML / 1.1规范中所指定,但使用此替代属性表示该脚本不包含document.write并告诉浏览器继续呈现。

Why? Scripts put at the bottom of the page can work great because scripts normally block parallel downloads, as specified in HTML/1.1 specs, but using this alternative attribute indicates that the script does not contain document.write and tells the browser to continue rendering.

以下是使用可以为moz渲染的defer属性的更好描述

这篇关于当使用“延迟”时,是否有必要将脚本放在页面底部?属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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