1

我创建了Field.jsindex.js. index.js使用字段。但是Field.js永远不会加载。我的沙箱在下面。

<script src="Field.js"></script>在codesandbox中不可能吗?它只适用于src="index.js"

这是我的沙箱 - https://codesandbox.io/s/l55933j36z

在此处输入图像描述

4

1 回答 1

1

这是我们如何侦听自定义事件的示例。这将允许您“等待”脚本并正常运行。

// This lives in you scrip dependancy.
const scriptReadyEvent = new CustomEvent('MyScriptLoaded', {
  bubbles: true
});

// Dummy a delay in loading a script
function demoDelay() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
    resolve('foo');
    }, 2000);
  });
}

// Listen for script loaded
document.addEventListener('MyScriptLoaded', () => {
  console.log('Script is loaded');
});

// The script would do this.
demoDelay().then(() => {
  document.dispatchEvent(scriptReadyEvent);
});

于 2019-02-15T19:14:14.537 回答