封装loadResources方法

This commit is contained in:
tangly1024
2022-02-18 11:06:25 +08:00
parent c369f567b1
commit 79b7aa4a37
3 changed files with 29 additions and 42 deletions

27
lib/utils.js Normal file
View File

@@ -0,0 +1,27 @@
// 封装异步加载资源的方法
/**
* 加载外部资源
* @param url 地址 例如 https://xx.com/xx.js
* @param type js 或 css
* @returns {Promise<unknown>}
*/
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)
}
})
}

View File

@@ -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)
}
})
}

View File

@@ -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([