-
-
Save matthewpenkala/dc7a08ba2ba9730b89baae778d1c1780 to your computer and use it in GitHub Desktop.
jQuery $.getScript() replacement via 100% vanilla JavaScript
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
// 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