js file实现
创建 JavaScript 文件的基本步骤
新建一个 .js 文件,例如 script.js,用于编写 JavaScript 代码。文件内容可以直接包含变量、函数或逻辑代码。
// 示例:定义一个函数并调用
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("World");
在 HTML 中引入 JavaScript 文件
通过 <script> 标签将 .js 文件链接到 HTML 中。推荐将 <script> 放在 <body> 末尾以提高页面加载性能。
<!DOCTYPE html>
<html>
<body>
<!-- 页面内容 -->
<script src="script.js"></script>
</body>
</html>
使用模块化开发(ES6 Modules)
通过 export 和 import 实现模块化。需在 <script> 标签中声明 type="module"。
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 输出 5
<!-- HTML 中引入模块 -->
<script type="module" src="main.js"></script>
动态加载 JavaScript 文件
使用 Promise 或 async/await 动态加载脚本,适用于按需加载场景。
function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// 使用示例
loadScript('dynamic.js')
.then(() => console.log('脚本加载成功'))
.catch(() => console.log('脚本加载失败'));
调试与错误处理
通过 try-catch 捕获运行时错误,结合 console 方法输出调试信息。
try {
// 可能出错的代码
const result = undefinedFunction();
} catch (error) {
console.error('错误捕获:', error.message);
}
代码压缩与优化
使用工具如 Webpack、Rollup 或 Terser 对 JavaScript 文件进行压缩和打包,减少体积并提升性能。
// 安装 Terser 并压缩文件
// npm install terser -g
// terser script.js -o script.min.js






