diff --git a/lib/utils.js b/lib/utils.js new file mode 100644 index 00000000..d3687ab9 --- /dev/null +++ b/lib/utils.js @@ -0,0 +1,27 @@ +// 封装异步加载资源的方法 + +/** + * 加载外部资源 + * @param url 地址 例如 https://xx.com/xx.js + * @param type js 或 css + * @returns {Promise} + */ +export 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) + } + }) +} diff --git a/themes/NEXT/components/Live2D.js b/themes/NEXT/components/Live2D.js index 5ad27c93..c9ce2a1b 100644 --- a/themes/NEXT/components/Live2D.js +++ b/themes/NEXT/components/Live2D.js @@ -1,5 +1,6 @@ /* eslint-disable no-undef */ import CONFIG_NEXT from '../config_next' +import { loadExternalResource } from '@/lib/utils' let hasLoad = false export default function Live2D () { @@ -29,24 +30,3 @@ function initLive2D () { }) } } - -// 封装异步加载资源的方法 -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) - } - }) -} diff --git a/themes/NEXT/components/Live2DWaifu.js b/themes/NEXT/components/Live2DWaifu.js index e79029ad..060eee4e 100644 --- a/themes/NEXT/components/Live2DWaifu.js +++ b/themes/NEXT/components/Live2DWaifu.js @@ -1,5 +1,6 @@ import Head from 'next/head' import { useEffect } from 'react' +import { loadExternalResource } from '@/lib/utils' export default function Live2DWife () { useEffect(() => { @@ -17,27 +18,6 @@ function initLive2DWife () { const live2dPath = 'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/' // const live2d_path = "/live2d-widget/"; - // 封装异步加载资源的方法 - 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) - } - }) - } - // 加载 waifu.css live2d.min.js waifu-tips.js if (screen.width >= 768) { Promise.all([