JavaScript: Inline Script with SRC Attribute JavaScript inline scripts are commonly included using the tag with a src attribute to load an external script file. However, can inline scripts be defined within the same <script> tag?</p> <p>According to the HTML 4.01 Specification, the behavior of a <script> tag with both an inline script and a src attribute is明确的:</p> <blockquote>如果src 属性未设置,用户代理必须将元素的内容解释为脚本。如果 src 有 URI 值,用户代理必须忽略元素的内容并通过 URI 检索脚本。 </blockquote> <p>这意味着 <script> 标签中的 src 属性具有优先级,inline 脚本将被忽略。也就是说,以下是有效的 JavaScript 使用方式:</p> <pre><code class="html"><script type='text/javascript' src='/path/to/script.js'> 将外部脚本加载到页面中,而无需执行任何inline 脚本。然而,以下用法是不正确的: alert('Do some stuff here, using resources defined in script.js.'); 在此示例中,inline 脚本将被忽略,因为 src 属性存在。要执行 inline 脚本,必须省略 src 属性: alert('Do some stuff here, using resources defined in script.js.');