带脚本延迟的空返回

问题描述

如果我像这样创建本地文件 def is_valid(code): code_letters = ["S","B","N","T","P"] letter_minimum = [1,3,4,3] letter_maximum = [7,9,6,7,5] if code[0] not in code_letters: return False index = code_letters.index(code[0]) num_range = (letter_minimum[index],letter_maximum[index]) validity = [] for i in code[1:]: if i == " ": continue try: i = int(i) if not (num_range[0] <= i <= num_range[1]): validity.append(False) except ValueError: validity.append(False) validity.append(True) return bool(all(validity) and validity)

Index.HTML

>>> is_valid('B747346')
True
>>> is_valid('N  444  454')
True
>>> is_valid('T 400 4854')    # Fails because 8 is out of the range [0,7].
False
>>> is_valid('S  444S454')    # Fails because 'S' is not a number
False
>>> is_valid('P  ')    # Fails because no numbers exist
False

然后在浏览器中打开文件,我会在控制台中看到 index.html。如果我从 <!doctype html> <html> <head> <meta charset="utf-8"> <script defer> let t = document.getElementById('top'); console.log(t); </script> </head> <body> <h1 id="top">Top Questions</h1> </body> </html> 更改为 null, 元素按预期返回。我以为 defer 保留了 type="module" 运行,直到 HTML 被解析。为什么 defer 在这方面不起作用 案例?

解决方法

defer 不适用于内联脚本。该属性不会做任何事情,就像 async 一样。如果要使用 defer,请使用外部脚本:

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

如果您使用“经典”(非模块)内联脚本,无论是 async 还是 defer 属性,它都会立即运行(除非类型对 JS 无效,其中以防它根本无法运行)。

作为 MDN says,带有 defer

如果 src 属性不存在(即用于内联脚本),则不得使用此属性,在这种情况下,它将不起作用。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...