【手搓一个原生全局loading组件解决页面闪烁问题】

页面闪烁效果1
页面闪烁效果2

封装一个全局loading组件

js 复制代码
class GlobalLoading extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
    }

    connectedCallback() {
        this.render();
        this.init();
    }

    render() {
        this.shadowRoot.innerHTML = `
            <style>
                .loading-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background-color: rgba(255, 255, 255, 0.9);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 9999;
                }

                .loading-spinner {
                    border: 4px solid #f3f3f3;
                    border-top: 4px solid #3498db;
                    border-radius: 50%;
                    width: 40px;
                    height: 40px;
                    animation: spin 1s linear infinite;
                }

                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            </style>
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
            </div>
        `;
    }

    init() {
        window.addEventListener('load', () => {
            setTimeout(() => {
                this.shadowRoot.querySelector('.loading-overlay').style.display = 'none';
            }, 500); // 延时 500 毫秒
        });
    }
}

customElements.define('global-loading', GlobalLoading);

引入全局 loading 组件

html 复制代码
<!-- 引入全局 loading 组件 -->
<script src="./components/global-loading.js" defer></script>

使用全局loading组件

html 复制代码
<!-- 使用全局 loading 组件 -->
<global-loading></global-loading>
相关推荐
Forfun_tt4 分钟前
xss-labs pass-12
前端·xss
云枫晖19 分钟前
Webpack系列-编译过程
前端·webpack
AskHarries29 分钟前
Toolhub — 一个干净实用的在线工具集合
前端·后端
H尗44 分钟前
Vue3响应式系统的精妙设计:深入理解 depsLength 与 trackId 的协同艺术
前端·vue.js
昔人'1 小时前
html`contenteditable`
前端·html
爱宇阳1 小时前
npm 常用标签与使用技巧新手教程
前端·npm·node.js
@大迁世界1 小时前
2025 年该选谁?npm vs yarn vs pnpm
前端·npm·node.js
crary,记忆1 小时前
简介NPM 和 NPX
前端·学习·npm·node.js
JianZhen✓1 小时前
现在在本地开发了一些代码A,又有了新需求要紧急开发代码B需要只上线代码B的代码,如何更好的处理这种情况
前端
郝学胜-神的一滴2 小时前
Cesium绘制线:从基础到高级技巧
前端·javascript·程序人生·线性代数·算法·矩阵·图形渲染