在JavaScript中,异步加载可以通过多种方式实现,例如使用<script>
标签、Promise
、async/await
或者fetch
API。处理异步加载错误的方法取决于你使用的具体方法。以下是几种常见方法的错误处理:
<script>
标签:<script src="your-script.js" onerror="handleError()"></script>
<script>
function handleError() {
console.error('Script loading failed');
}
</script>
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);
});
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);
}
})();
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异步加载错误。请根据你的需求和实际情况选择合适的方法。