在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異步加載錯誤。請根據你的需求和實際情況選擇合適的方法。