HTML与JavaScript交互的核心方法
通过三种标准化方式实现脚本调用:
<div class="code-example">
<h3>1. 内联脚本执行</h3>
<pre><code><button onclick="handleClick()">交互元素</button>
<script>
function handleClick() {
console.log(‘DOM事件触发’);
}
</script>
️ 仅建议微交互场景使用,避免影响页面加载速度
<div class="code-example optimized">
<h3>2. 外链脚本最佳实践</h3>
<pre><code><script src="app.min.js" <mark>defer</mark> integrity="sha256-xxxx" crossorigin="anonymous"></script></code></pre>
<ul class="feature-list">
<li><span class="icon-check"></span> 使用CDN加速:<code>https://cdn.example.com/app.js</code></li>
<li><span class="icon-shield"></span> 子资源完整性校验(SRI)</li>
<li><span class="icon-gauge"></span> 延迟加载策略:defer/async属性对比</li>
</ul>
</div>
</div>
<!-- 性能优化 -->
<div class="section-block accent">
<h2>现代Web性能增强方案</h2>
<div class="comparison-table">
<table>
<thead>
<tr>
<th>加载方式</th>
<th>执行时机</th>
<th>适用场景</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><script></code> (默认)</td>
<td>立即阻塞解析</td>
<td>关键初始化脚本</td>
</tr>
<tr>
<td><code>async</code></td>
<td>下载完成立即执行</td>
<td>独立统计分析代码</td>
</tr>
<tr>
<td><code>defer</code></td>
<td>DOM解析完成后执行</td>
<td>多数功能脚本</td>
</tr>
</tbody>
</table>
</div>
<div class="pro-tip">
<h3>动态加载策略</h3>
<pre><code>const script = document.createElement('script');
script.src = ‘dynamic-component.js’;
script.onload = initComponent;
document.body.appendChild(script);