Skip to content

Instantly share code, notes, and snippets.

@jr-codes
Last active May 2, 2024 02:45
Show Gist options
  • Save jr-codes/1893296 to your computer and use it in GitHub Desktop.
Save jr-codes/1893296 to your computer and use it in GitHub Desktop.
include(): JavaScript function for dynamically including a CSS or JS file on a page
/**
* Includes the CSS or JS file into the head of the page.
*
* Examples:
* include('http://example.com/script.js')
* include('http://example.com/style.css')
* include('http://example.com/script.php', 'js')
* @param {string} url URL of the CSS or JS file
* @param {string} [type] 'css' or 'js' to specify the type of file.
* This parameter is optional, but it should be
* used if the url does not end in '.css' or '.js'.
*/
const include = (url, type = url.split('.').pop()).toLowerCase(), onload = function() {}, onerror = function() {}) => {
let elem;
if (type === 'css') {
elem = document.createElement('link');
elem.rel = 'stylesheet';
elem.href = url;
} else if (type === 'js') {
elem = document.createElement('script');
elem.src = url;
elem.async = false;
} else {
throw new Error('Failed to include ' + url + ' due to unknown file type.');
}
elem.onload = onload;
elem.onerror = onerror;
document.head.appendChild(elem);
}
/**
* Includes the CSS or JS file into the head of the page.
*
* Examples:
* include('http://example.com/script.js')
* include('http://example.com/style.css')
* include('http://example.com/script.php', 'js')
* @param {string} url URL of the CSS or JS file
* @param {string} [type] 'css' or 'js' to specify the type of file.
* This parameter is optional, but it should be
* used if the url does not end in '.css' or '.js'.
*/
const include = (url, type = url.split('.').pop().toLowerCase()) => new Promise((resolve, reject) => {
let elem;
if (type === 'css') {
elem = document.createElement('link');
elem.rel = 'stylesheet';
elem.href = url;
} else if (type === 'js') {
elem = document.createElement('script');
elem.src = url;
elem.async = false;
} else {
throw new Error('Failed to include ' + url + ' due to unknown file type.');
}
elem.onload = resolve;
elem.onerror = reject;
document.head.appendChild(elem);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment