Skip to content

Instantly share code, notes, and snippets.

@matthewpenkala
Forked from kmonsoor/getScript.js
Last active February 3, 2024 09:29
Show Gist options
  • Save matthewpenkala/dc7a08ba2ba9730b89baae778d1c1780 to your computer and use it in GitHub Desktop.
Save matthewpenkala/dc7a08ba2ba9730b89baae778d1c1780 to your computer and use it in GitHub Desktop.
jQuery $.getScript() replacement via 100% vanilla JavaScript
// Vanilla JavaScript function for dynamic script loading with improved caching and optional callback
const getScriptVanilla = async (source, callback) => {
try {
const response = await fetch(source, {
method: 'GET',
headers: {
'Accept': '*/*',
'Sec-Fetch-Dest': 'script'
},
cache: 'force-cache' // Utilizes cache aggressively, falling back to network if unavailable
});
if (!response.ok) {
throw new Error('Network response was not ok.');
}
const scriptText = await response.text();
// Create a new function and execute the script text
const scriptFunction = new Function(scriptText);
scriptFunction();
if (callback) {
callback();
}
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
};
// Usage
getScriptVanilla(script_src, () => {
console.log('The script has been loaded and executed.');
// You can add any further code that depends on the loaded script here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment