JavaScript 的 type 有哪些
主要类型及用途
1. text/javascript (默认值)
<script type="text/javascript"> console.log("JavaScript代码"); </script>
用途: 标准的JavaScript代码,现代浏览器中
type
属性可省略
2. application/ld+json
<script type="application/ld+json"> {"@context": "https://schema.org","@type": "Organization","name": "示例公司" } </script>
用途: 用于结构化数据(JSON-LD格式),帮助搜索引擎理解页面内容
3. application/json
<script type="application/json"> {"appName": "我的应用","version": "1.0.0" } </script>
用途: 通用的JSON数据,用于存储配置数据或应用数据
4. module
<script type="module"> import { functionName } from './module.js'; </script>
用途: 表示脚本是ES6模块,支持import/export语法
5. importmap
<script type="importmap"> {"imports": {"lodash": "/node_modules/lodash-es/lodash.js"} } </script>
用途: 定义模块导入映射,用于ES6模块的别名解析
6. application/ecmascript
<script type="application/ecmascript"> // ECMAScript代码 </script>
用途: 与text/javascript类似,较少使用
7. text/plain
<script type="text/plain" data-type="config"> 这是一段纯文本,不会被作为脚本执行 </script>
用途: 存储纯文本数据,浏览器不会执行
8. text/x-handlebars-template
<script type="text/x-handlebars-template" id="template"> <div>{{name}}</div> </script>
用途: Handlebars模板,不会被作为脚本执行
9. text/x-template (Vue.js)
<script type="text/x-template" id="my-template"> <div>{{ message }}</div> </script>
用途: Vue.js的模板定义方式
10. text/html
<script type="text/html" id="template"> <div class="item">HTML内容</div> </script>
用途: 存储HTML模板片段
完整示例
<!DOCTYPE html>
<html>
<head><!-- JSON-LD 结构化数据 --><script type="application/ld+json">{"@context": "https://schema.org","@type": "WebSite","name": "我的网站"}</script><!-- 应用配置 --><script type="application/json" id="app-config">{"apiUrl": "https://api.example.com","theme": "dark"}</script><!-- ES6 模块 --><script type="module">import { initApp } from './app.js';initApp();</script><!-- 导入映射 --><script type="importmap">{"imports": {"components": "/js/components/index.js"}}</script><!-- 模板 --><script type="text/x-template" id="user-card"><div class="user-card"><h3>{{name}}</h3><p>{{email}}</p></div></script>
</head>
<body><!-- 传统JavaScript --><script>// 传统脚本console.log("页面加载完成");</script>
</body>
</html>
注意事项
MIME类型规则:
type
属性值应该是有效的MIME类型默认行为: 如果不指定
type
或使用text/javascript
,浏览器会执行脚本非JavaScript类型: 当类型不是JavaScript时,浏览器不会执行其中的代码
模块脚本:
type="module"
的脚本默认具有defer特性