Last active
November 29, 2023 13:19
-
-
Save maalos/f955d555e3561813c5df49a5c528e0a2 to your computer and use it in GitHub Desktop.
A useful JavaScript snippet for loading JavaScript files (especially the big ones, slowing down website load times) after the website has loaded, in order specified in scriptsToLoad.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
<script src="syncedDeferLoader.js" defer></script> | |
</head> | |
<body> | |
</body> | |
</html> |
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
var scriptsToLoad = [ | |
'https://code.jquery.com/jquery-3.7.1.min.js', | |
'someScriptThatRequiresJQuery.js', | |
]; | |
(() => { | |
function loadScript(src, callback) { | |
var script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = src; | |
script.onreadystatechange = callback; | |
script.onload = callback; | |
document.getElementsByTagName('head')[0].appendChild(script); | |
}; | |
function loadScriptsSequentially(scripts, index) { | |
index = index || 0; | |
if (index < scripts.length) { | |
loadScript(scripts[index], () => { | |
loadScriptsSequentially(scripts, index + 1); | |
}); | |
} | |
}; | |
loadScriptsSequentially(scriptsToLoad); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment