Created
September 14, 2025 08:23
-
-
Save saeedvir/9de01384d546b9118124a4573a1a2bb8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
const scripts = [ | |
'https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js', // ✅ Valid | |
'https://example.com/nonexistent-script.js', // ❌ 404 — THIS WILL BREAK SEQUENCE | |
'https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js' // ⛔ Won't load due to previous error | |
]; | |
try { | |
const loadedScripts = await loadScriptsSequentiallyEnhanced(scripts, { timeout: 5000 }); | |
} catch (error) { | |
console.log(error.stack ? error.stack.slice(0, 500) + '...' : error.message); | |
} | |
*/ | |
function loadScripts(sources, options = {}) { | |
const timeoutMs = options.timeout || 8000; | |
return sources.reduce((promise, src) => { | |
return promise.then(async () => { | |
return new Promise((resolve, reject) => { | |
const script = document.createElement('script'); | |
script.src = src; | |
let timedOut = false; | |
const timeoutId = setTimeout(() => { | |
timedOut = true; | |
script.remove(); // Clean up DOM | |
reject(new Error(`⏰ Timeout after ${timeoutMs}ms: ${src}`)); | |
}, timeoutMs); | |
script.onload = () => { | |
clearTimeout(timeoutId); | |
if (!timedOut) resolve(script); | |
}; | |
script.onerror = () => { | |
clearTimeout(timeoutId); | |
if (!timedOut) { | |
reject(new Error(`❌ Network/404 error: ${src}`)); | |
} | |
}; | |
document.head.appendChild(script); | |
// console.log(`📥 Loading: ${src}`); | |
}); | |
}); | |
}, Promise.resolve()); | |
} | |
/* | |
loadScript('https://example.com/script.js', (error) => { | |
if (error) { | |
console.error(error); | |
} else { | |
console.log('Script loaded successfully.'); | |
// Use functions from the script here | |
} | |
}); | |
*/ | |
function loadScript(src, callback) { | |
const script = document.createElement('script'); | |
script.src = src; | |
script.onload = () => callback(null); | |
script.onerror = () => callback(new Error(`Script load failed for ${src}`)); | |
document.head.appendChild(script); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment