javascript - 为什么导入JS文件时script标签需要留空?

标签 javascript html

我正在学习 JavaScript 以及 HTML 和 CSS。我编写了 JavaScript 文件 Primes.js,其中包含一些用于测试的素数查找相关函数。

为了使用外部 .js 文件进行测试,我编写了以下 HTML 文件:

...
<body>
    <script src="Primes.js">
        console.log("Loaded...");

        var n = 13;
        alert(n + " is prime?: " + isPrime(n));

        console.log("Ending...");
    </script>
</body>
...

但它从未执行脚本 block 内的语句。

环顾四周,我发现this answer ,并将正文更改为:

...
<body>
    <script src="Primes.js"></script>
    <script>
        console.log("Loaded...");

        var n = 13;
        alert(n + " is prime?: " + isPrime(n));

        console.log("Ending...");
    </script>
</body>
...

神奇的是,它按预期工作了。需要空脚本标签来导入文件似乎很奇怪。

为什么要求导入.js文件的脚本标签为空?如果脚本是其使用的同一标签中的源,是否会产生后果?

最佳答案

w3c 中所写当 src 属性存在时,脚本内的内容应该用于脚本的文档。

If a script element's src attribute is specified, then the contents of the script element, if any, must be such that the value of the text IDL attribute, which is derived from the element's contents, matches the documentation production in the following ABNF, the character set for which is Unicode.

关于javascript - 为什么导入JS文件时script标签需要留空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030228/

相关文章:

javascript - 如何编写具有异步设置和拆卸操作的测试?

javascript - JavaScript 新手。这段代码有什么问题?

css - 媒体查询无法为任何版本的 IE 工作

html - 在 Chrome 中使用多列布局中断覆盖 div

jquery - 通过拖动调整div的大小

javascript - 如何读取表单中的输入数据?

javascript - 随机数生成器产生有偏差的结果 - 没有明确的原因

javascript - 根据先前的 Ajax 调用,根据用户确认执行 Ajax 调用

javascript - Chrome 扩展程序的跟踪 URL

javascript - ajaxstart 在toggle() 事件中触发,但无法在完成时触发ajaxstop