Created
July 29, 2016 09:13
-
-
Save spiralx/8b8d91fc46d09e07f8d499f7902f7fe0 to your computer and use it in GitHub Desktop.
Find and inject libraries from cdnjs by name
This file contains hidden or 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
/* jshint asi: true, esnext: true */ | |
(() => { | |
'use strict' | |
const BOLD = 'font-weight: bold;', | |
LINK = 'text-decoration: underline; color: #03d', | |
RESET = 'font-weight: normal; text-decoration: none; color: black; background-color: white; display: inline' | |
// ---------------------------------------------------------- | |
const findElement = (tag, attr = {}) => !!document.querySelector(tag + Object.keys(attr).map(k => `[${k}="${attr[k]}"]`).join('')) | |
// ---------------------------------------------------------- | |
const EL = (tag, attr = {}) => new Promise((onload, onerror) => { | |
const e = Object.assign(document.createElement(tag), attr, { onload, onerror }) | |
document.body.appendChild(e) | |
}) | |
// ---------------------------------------------------------- | |
console.inject = (library, force) => new Promise((resolve, reject) => { | |
if (!force || findElement('script', { 'data-query': library })) { | |
console.info(`Library %c"${library}"%c already injected`, BOLD, RESET) | |
resolve(library) | |
} | |
// https://api.cdnjs.com/libraries?search=url&fields=name,description,version.,author,homepage,license,repository,keywords,autoupdate,latest,assets | |
const url = `https://api.cdnjs.com/libraries?search=${library}` | |
fetch(url) | |
.then(response => response.ok && response.json()) | |
.then(json => { | |
const { total, results } = json | |
const lib_re = RegExp(`^${library}(\\.js)?$`, 'i') | |
const m = results.find(r => lib_re.test(r.name)) | |
if (m) { | |
const src = m.latest.replace(/^http:/, 'https:') | |
EL('script', { | |
src, | |
'data-query': library | |
}) | |
.then( | |
() => { | |
console.info(`Library %c"${library}"%c injected from %c${src}%c`, BOLD, RESET, LINK, RESET) | |
resolve(library) | |
}, | |
() => { | |
console.warn(`Library %c"${library}"%c from %c${src}%c failed on load!`, BOLD, RESET, LINK, RESET) | |
reject(library) | |
} | |
) | |
} else { | |
console.warn(`Library %c"${library}"%c not found!`, BOLD, RESET) | |
reject(library) | |
} | |
}) | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment