Skip to content

Instantly share code, notes, and snippets.

@saeedvir
Created May 1, 2025 03:35
Show Gist options
  • Save saeedvir/dfde2052035b3300cc3606bb409f8870 to your computer and use it in GitHub Desktop.
Save saeedvir/dfde2052035b3300cc3606bb409f8870 to your computer and use it in GitHub Desktop.
Injects an external resource (script or stylesheet) into the current HTML document
/**
* Injects an external resource (script or stylesheet) into the current HTML document
*
* @param {string} url - The URL of the resource to inject
* @param {string} type - The type of resource ('script' or 'style')
* @param {function} [callback] - Optional callback function (only for scripts) that executes after loading
*/
function injectResource(url, type, callback) {
// Variable to hold the DOM element we'll create
let element;
// Create the appropriate element based on resource type
if (type === 'script') {
// Create a script element for JavaScript files
element = document.createElement('script');
element.src = url; // Set the source URL
element.type = 'text/javascript'; // Set the MIME type
} else if (type === 'style') {
// Create a link element for CSS files
element = document.createElement('link');
element.href = url; // Set the resource URL
element.rel = 'stylesheet'; // Define the relationship as stylesheet
element.type = 'text/css'; // Set the MIME type
}
// Only add onload callback for scripts (stylesheets don't have consistent onload support)
if (callback && type === 'script') {
element.onload = callback; // Execute callback after script loads
}
// Append the element to the document head
// This triggers the actual loading of the resource
document.head.appendChild(element);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment