javascript封装异步加载资源的方法

// 封装异步加载资源的方法
function loadExternalResource(url, type) {
	return new Promise((resolve, reject) => {
		let tag;
		if (type === "css") {
			tag = document.createElement("link");
			tag.rel = "stylesheet";
			tag.href = url;
		}
		else if (type === "js") {
			tag = document.createElement("script");
			tag.src = url;
		}
		if (tag) {
			tag.onload = () => resolve(url);
			tag.onerror = () => reject(url);
			document.head.appendChild(tag);
		}
	});
}
Promise.all([
	loadExternalResource("style.css", "css"),
	loadExternalResource("style.js", "js"),
]).then(() => {
	//执行
});

你可能感兴趣的:(JavaScript,前端,javascript,前端,开发语言)