Last active
February 11, 2025 03:04
-
-
Save saeedvir/54e852a72b22d85b1201d10dda5cfda9 to your computer and use it in GitHub Desktop.
This JavaScript snippet dynamically loads external scripts with a delay after the page has fully loaded.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Script Loader Example</title> | |
</head> | |
<body> | |
<h1>Script Loading Example</h1> | |
<script> | |
function loadScript(url) { | |
return new Promise(function(resolve, reject) { | |
let script = document.createElement('script'); | |
script.src = url; | |
script.async = false; // Ensures execution order is maintained | |
script.onload = function() { | |
resolve(url); | |
}; | |
script.onerror = function() { | |
reject(url); | |
}; | |
document.body.appendChild(script); | |
}); | |
} | |
function start_app(){ | |
alert('start_app'); | |
} | |
let promises = []; | |
let scripts = [ | |
"https://code.jquery.com/jquery-3.6.0.min.js", // A valid script | |
//"https://invalid-url.com/script.js" // An invalid script to test error handling | |
]; | |
let delayTime = 3000; //ms | |
document.addEventListener("DOMContentLoaded", function(event) { | |
setTimeout(() => { | |
scripts.forEach(function(url) { | |
promises.push(loadScript(url)); | |
}); | |
Promise.all(promises) | |
.then(function() { | |
console.log('All scripts loaded successfully'); | |
start_app(); | |
}) | |
.catch(function(script) { | |
console.log(script + ' failed to load'); | |
}); | |
}, delayTime); // Delay of 3 seconds | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment