Java

JavaScript异步加载怎样处理错误

小樊
86
2024-10-24 11:33:26
栏目: 编程语言

在JavaScript中,异步加载可以通过多种方式实现,例如使用<script>标签、Promiseasync/await或者fetch API。处理异步加载错误的方法取决于你使用的具体方法。以下是几种常见方法的错误处理:

  1. 使用<script>标签:
<script src="your-script.js" onerror="handleError()"></script>
<script>
  function handleError() {
    console.error('Script loading failed');
  }
</script>
  1. 使用Promise
function loadScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

loadScript('your-script.js')
  .then(() => {
    console.log('Script loaded successfully');
  })
  .catch((error) => {
    console.error('Script loading failed:', error);
  });
  1. 使用async/await
async function loadScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

(async () => {
  try {
    await loadScript('your-script.js');
    console.log('Script loaded successfully');
  } catch (error) {
    console.error('Script loading failed:', error);
  }
})();
  1. 使用fetch API:
async function loadScript(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Script loading failed with status ${response.status}`);
    }
    const script = document.createElement('script');
    script.text = await response.text();
    document.head.appendChild(script);
  } catch (error) {
    console.error('Script loading failed:', error);
  }
}

loadScript('your-script.js');

以上示例展示了如何使用不同方法处理JavaScript异步加载错误。请根据你的需求和实际情况选择合适的方法。

0
看了该问题的人还看了