|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
script 和 noscript 元素
script
script 元素是用于在网页中嵌入 JavaScript 脚本的。例如:
- <!DOCTYPE html>
- <html>
- <head></head>
- <body>
- <script>
- document.write("Hello");
- </script>
- </body>
- </html>
复制代码
执行这个 html 文件,将会在页面上显示 Hello。
script 元素还可以链接外部的 JS 文件,例如:
- <!DOCTYPE html>
- <html>
- <head></head>
- <body>
- <script src="a.js"></script>
- </body>
- </html>
复制代码
a.js:
执行 html 文件,一样会在页面显示 Hello。
注意:链接了外部的 JS 文件,<script> 标签内部不能再有 JS 代码。例如下面这段代码是错误的:
- <script src="a.js">
- document.write("123")
- </script>
复制代码
正常情况下,HTML 被解析时遇到了 JS 代码时会停下解析 HTML 代码,转而执行 JS 代码。我们可以延迟 JS 代码的执行,等到 HTML 代码解析完后再执行 JS 代码:
- <!DOCTYPE html>
- <html>
- <head></head>
- <body>
- <!-- defer 属性用于延迟 JS 代码的执行 -->
- <script src="a.js" defer></script>
- </body>
- </html>
复制代码
还可以异步执行 JS 代码(JS 代码和 HTML diamante同时解析):
- <!DOCTYPE html>
- <html>
- <head></head>
- <body>
- <!-- 设置 async 属性 -->
- <script src="a.js" defer></script>
- </body>
- </html>
复制代码
defer、async 只能用于外部代码文件。
noscript
当浏览器不支持 JavaScript 时,我们可以用 noscript 元素显示一些内容:
- <!DOCTYPE html>
- <html>
- <head></head>
- <body>
- <script>
- document.write("欢迎你,让我们开启 JavaScript 的旅程吧!");
- </script>
- <noscript>
- <p>都什么年代了,没有 JavaScript 哪行?!</p>
- <img
- alt="嫌弃"
- src="https://ilovefishc.com/html5/html5/lesson6/img/xianqi.png"
- />
- </noscript>
- </body>
- </html>
复制代码
运行这段 HTML 代码,一般是可以正常显示 "欢迎你,让我们开启 JavaScript 的旅程吧!" 的,如下图:
但当浏览器不支持 JavaScript 或者用户禁用了 JavaScript 时,会显示如下的内容:
|
|