refactor: optimize code

This commit is contained in:
younglei 2022-06-14 21:13:10 +08:00
parent b6a24b71eb
commit 6f18c6fbfb
2 changed files with 38 additions and 36 deletions

View File

@ -1,19 +0,0 @@
import { useLoading } from './loading'
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
return new Promise(resolve => {
if (condition.includes(document.readyState)) {
resolve(true)
} else {
document.addEventListener('readystatechange', () => {
if (condition.includes(document.readyState)) {
resolve(true)
}
})
}
})
}
const { appendLoading, removeLoading } = useLoading()
window.removeLoading = removeLoading
domReady().then(appendLoading)

View File

@ -1,10 +1,38 @@
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
return new Promise(resolve => {
if (condition.includes(document.readyState)) {
resolve(true)
} else {
document.addEventListener('readystatechange', () => {
if (condition.includes(document.readyState)) {
resolve(true)
}
})
}
})
}
const safeDOM = {
append(parent: HTMLElement, child: HTMLElement) {
if (!Array.from(parent.children).find(e => e === child)) {
return parent.appendChild(child)
}
},
remove(parent: HTMLElement, child: HTMLElement) {
if (Array.from(parent.children).find(e => e === child)) {
return parent.removeChild(child)
}
},
}
/**
* https://tobiasahlin.com/spinkit
* https://connoratherton.com/loaders
* https://projects.lukehaas.me/css-loaders
* https://matejkustec.github.io/SpinThatShit
*/
export function useLoading() {
function useLoading() {
const className = `loaders-css__square-spin`
const styleContent = `
@keyframes square-spin {
@ -43,25 +71,18 @@
return {
appendLoading() {
safe.append(document.head, oStyle)
safe.append(document.body, oDiv)
safeDOM.append(document.head, oStyle)
safeDOM.append(document.body, oDiv)
},
removeLoading() {
safe.remove(document.head, oStyle)
safe.remove(document.body, oDiv)
safeDOM.remove(document.head, oStyle)
safeDOM.remove(document.body, oDiv)
},
}
}
const safe = {
append(parent: HTMLElement, child: HTMLElement) {
if (!Array.from(parent.children).find(e => e === child)) {
return parent.appendChild(child)
}
},
remove(parent: HTMLElement, child: HTMLElement) {
if (Array.from(parent.children).find(e => e === child)) {
return parent.removeChild(child)
}
},
}
// ----------------------------------------------------------------------
const { appendLoading, removeLoading } = useLoading()
window.removeLoading = removeLoading
domReady().then(appendLoading)