JavaScript异步加载怎样处理错误

avatar
作者
猴君
阅读量:0

在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异步加载错误。请根据你的需求和实际情况选择合适的方法。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!