Skip to content

Instantly share code, notes, and snippets.

@maalos
Last active November 29, 2023 13:19
Show Gist options
  • Save maalos/f955d555e3561813c5df49a5c528e0a2 to your computer and use it in GitHub Desktop.
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.
<!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>
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