UNPKG

load-remote

Version:

在 web 项目中引用载入远程资源(css, js),基于<link>/<script>标签实现。Used to load remote resources(CSS/JS) in a web project , based on the html tag(<link>/<script>).

77 lines (63 loc) 2.14 kB
/** * Bundle of load-remote * Generated: 2020-03-14 * Version: 1.0.2 * License: MIT * Author: 2631541504@qq.com */ import { promiseOnPending } from '@livelybone/singleton'; /** * @param node * @param parentNode Default: document.head * */ function injectToHtml(node, parentNode) { var id = node.id; if (!document.getElementById(id)) { var $parentNode = parentNode || document.head; var $node = 'gnt' in node ? node.gnt() : node; $node.id = id; $parentNode.appendChild($node); } } function loadRemote(url, options) { if (!url) return Promise.reject(new Error('The params url should not be empty')); var id = options && options.id || url; return promiseOnPending(function () { return new Promise(function (res, rej) { var target = document.getElementById(id); if (target) return res({ target: target }); var isCss = /\.css$/.test(url); var isJs = /\.js$/.test(url); var tagName = options && options.tagName || (isCss ? 'link' : isJs ? 'script' : ''); if (!tagName) { return rej(new Error('Please set the tagName of this remote resource')); } var type = options && options.type || (isCss ? 'text/css' : isJs ? 'text/javascript' : ''); if (!type) { return rej(new Error('Please provide the type attribute of this remote resource')); } var rel = options && options.rel || (isCss ? 'stylesheet' : isJs ? 'prefetch' : ''); var charset = options && options.charset || 'utf-8'; var injectParentElement = options && options.injectParentElement || document.head; var el = document.createElement(tagName); el.type = type; el.charset = charset; if (id) el.id = id; if (tagName === 'link') { if (rel) el.setAttribute('rel', rel); el.setAttribute('href', url); } else el.setAttribute('src', url); el.onload = res; el.onerror = function (e) { rej(e); injectParentElement.removeChild(el); }; injectParentElement.appendChild(el); }); }, { id: id }); } export { injectToHtml, loadRemote };