如何在JavaScript模块中导入GeoGebra小程序代码并解决加载错误?
在ES6模块中使用GeoGebra的解决方法
问题场景
当尝试在type="module"的script标签中直接导入GeoGebra的deployggb.js时,会触发如下错误:
Uncaught ReferenceError: __gwt_getMetaProperty is not defined at B (deployggb.js:5:36382) at webModule (deployggb.js:5:38593) at injectHTML5Applet (deployggb.js:5:14606) at continueInject (deployggb.js:5:4385) at Object.GGBApplet.applet.inject (deployggb.js:5:3255)
对应的错误代码示例:
<script type="module"> import 'https://cdn.geogebra.org/apps/deployggb.js' const el = document.getElementById('ggb') const params = { appName: 'classic' } const applet = new GGBApplet(params, true) applet.inject(el) </script>
解决方案
由于deployggb.js并非标准ES模块,而是面向全局环境的传统脚本,直接用import导入会打乱它的初始化逻辑。我们需要在模块中动态加载该脚本,确保脚本在全局环境中执行完成后再初始化GeoGebra。
代码实现
<script type="module"> // 封装脚本加载逻辑 async function loadGeoGebraScript() { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = 'https://cdn.geogebra.org/apps/deployggb.js'; script.onload = resolve; script.onerror = () => reject(new Error('GeoGebra脚本加载失败')); document.head.appendChild(script); }); } // 初始化GeoGebra async function initGeoGebra() { try { await loadGeoGebraScript(); const container = document.getElementById('ggb'); const appParams = { appName: 'classic' }; const applet = new GGBApplet(appParams, true); applet.inject(container); } catch (err) { console.error('初始化GeoGebra出错:', err); } } // 执行初始化 initGeoGebra(); </script>
原因说明
deployggb.js依赖全局环境来初始化内部变量(比如__gwt_getMetaProperty),直接用ES模块的import导入时,脚本会在模块作用域中执行,无法正确绑定这些全局依赖,进而触发错误。动态创建script标签的方式和传统<script src="...">的加载逻辑一致,能保证脚本在全局作用域中完成初始化,所有依赖的全局变量都能正常生成。
内容的提问来源于stack exchange,提问作者Glen Whitney
相关产品推荐
相关产品推荐

