Stencil.js项目中引入外部script.js文件失效问题求助
解决Stencil.js中外部script文件无法生效的问题
问题根源
- 外部脚本放在
<head>中时,执行时机早于DOM元素渲染,querySelector找不到<booker-buttons>和<booker-form>元素 - Stencil.js的自定义组件是异步注册的,即使DOM渲染完成,组件可能还未完成定义,直接调用组件方法会失败
解决方案
步骤1:调整外部脚本的加载位置
把<script src="./script.js"></script>从<head>移到</body>标签的前一行,确保脚本执行时DOM结构已经完整:
<!-- 调整后的index.html --> <!DOCTYPE html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <title>Booker App</title> <meta name="Description" content="Welcome to the Stencil App Starter. You can use this starter to build entire apps all with web components using Stencil!"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0"> <meta name="theme-color" content="#16161d"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta http-equiv="x-ua-compatible" content="IE=Edge"> <script type="module" src="/build/app.esm.js"></script> <script nomodule src="/build/app.js"></script> <link href="/build/app.css" rel="stylesheet"> <link rel="manifest" href="/manifest.json"> </head> <body> <booker-header></booker-header> <booker-display></booker-display> <booker-buttons name="Add Books"></booker-buttons> <booker-form></booker-form> <!-- 把外部脚本移到这里 --> <script src="./script.js"></script> </body> </html>
步骤2:确保Stencil组件注册完成后再执行代码
修改script.js,通过customElements.whenDefined等待目标组件完成注册,再绑定事件和调用方法:
// script.js // 等待两个自定义组件注册完成 Promise.all([ customElements.whenDefined('booker-buttons'), customElements.whenDefined('booker-form') ]).then(() => { const btn = document.querySelector('booker-buttons'); const form = document.querySelector('booker-form'); // 绑定点击事件 btn.addEventListener('click', () => { console.log('testing if file works'); form.open(); }); });
额外检查:确认脚本路径正确
确保script.js和index.html在同一目录下,如果不在,需要调整src属性的路径(比如放在js文件夹下的话,路径应为./js/script.js)。
内容的提问来源于stack exchange,提问作者Tom Orn
相关产品推荐
相关产品推荐

