Last active
January 27, 2025 10:22
-
-
Save aslafy-z/70ef758cf607a417de1b5f4d3884250f to your computer and use it in GitHub Desktop.
This file contains 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
function loadResource(type, sources) { | |
let index = 0; | |
function tryLoad() { | |
if (index >= sources.length) { | |
console.error(`${type.toUpperCase()} load failed.`); | |
return; | |
} | |
let el = type === 'js' ? document.createElement('script') : document.createElement('link'); | |
if (type === 'js') { | |
el.src = sources[index]; | |
el.onload = () => console.log(`Loaded: ${sources[index]}`); | |
el.onerror = () => { | |
console.warn(`Failed: ${sources[index]}`); | |
index++; | |
tryLoad(); | |
}; | |
} else if (type === 'css') { | |
el.rel = 'stylesheet'; | |
el.href = sources[index]; | |
el.onload = () => console.log(`Loaded: ${sources[index]}`); | |
el.onerror = () => { | |
console.warn(`Failed: ${sources[index]}`); | |
index++; | |
tryLoad(); | |
}; | |
} else { | |
console.error('Invalid type'); | |
return; | |
} | |
document.head.appendChild(el); | |
} | |
tryLoad(); | |
} | |
// Usage examples | |
loadResource('js', [ | |
'local-tailwind.js', | |
'https://cdn.jsdelivr.net/npm/[email protected]/tailwindcss.js', | |
'https://unpkg.com/[email protected]/dist/tailwindcss.js' | |
]); | |
loadResource('css', [ | |
'local-tailwind.css', | |
'https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css', | |
'https://unpkg.com/[email protected]/dist/tailwind.min.css' | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment