我们有时候会在网页中的<script>段中看到defer关键字,那么它到底是派什么用处呢?
defer从字面意思上来看就是延迟,推迟的意思。它的目的在于:
让浏览器在下载脚本的时候就不必立即对其进行处理,而是继续对页面进行下载和解析,
等到全部页面下载完成后执行JS脚本。这样做有时候能够提高下载的性能。
那么defer的应用有什么呢?
我们经常会用innerHTML来动态给DOM元素加载JS,比如:
object.innerHTML = "<script" + ">"..."</script" + ">";
但是当你调用你这个新定义的动态JS经常会出错,说还未定义,
解决方法是给<script>加上defer。
在下面的代码中你可以试下把 defer去掉程序就会出错:
















