From e35894c60d022f52403da81f5ab03b15b13df5b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=AF=E5=9B=BD=E6=B8=85?= <994599292@qq.com> Date: Wed, 4 Dec 2019 20:59:27 +0800 Subject: [PATCH] Fix issues caused by onload event: initWidget is not defined (#12) --- autoload.js | 47 ++++++++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/autoload.js b/autoload.js index 5c2763b..f466e4b 100644 --- a/autoload.js +++ b/autoload.js @@ -2,30 +2,39 @@ const live2d_path = "https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget/"; //const live2d_path = "/live2d-widget/"; -//加载waifu.css -$("").attr({ href: live2d_path + "waifu.css", rel: "stylesheet" }).appendTo("head"); +//封装异步加载资源的方法 +function loadExternalResource(url, type) { + return new Promise((resolve, reject) => { + let tag; -//加载live2d.min.js -$.ajax({ - url: live2d_path + "live2d.min.js", - dataType: "script", - cache: true -}); + 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); + } + }); +} -//加载waifu-tips.js -$.ajax({ - url: live2d_path + "waifu-tips.js", - dataType: "script", - cache: true -}); - -//初始化看板娘,会自动加载指定目录下的waifu-tips.json -$(window).on("load", function() { +//加载waifu.css live2d.min.js waifu-tips.js +Promise.all([ + loadExternalResource(live2d_path + "waifu.css", "css"), + loadExternalResource(live2d_path + "live2d.min.js", "js"), + loadExternalResource(live2d_path + "waifu-tips.js", "js") +]).then(() => { initWidget(live2d_path + "waifu-tips.json", "https://live2d.fghrsh.net/api"); }); -//initWidget第一个参数为waifu-tips.json的路径 -//第二个参数为api地址(无需修改) +//initWidget第一个参数为waifu-tips.json的路径,第二个参数为api地址 //api后端可自行搭建,参考https://github.com/fghrsh/live2d_api +//初始化看板娘会自动加载指定目录下的waifu-tips.json console.log(` く__,.ヘヽ. / ,ー、 〉