Skip to content

Instantly share code, notes, and snippets.

@dinh
Forked from jr-codes/include-callback.js
Created December 21, 2022 21:39
Show Gist options
  • Save dinh/b39f4c6df87b55422caf28a57d866c95 to your computer and use it in GitHub Desktop.
Save dinh/b39f4c6df87b55422caf28a57d866c95 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