1.基本理解
骨架屏實現原理很簡單,就是通過占位線框元素,漸進式加載數據。
骨架屏是結合了懶加載功能,在頁面沒有加載完成之前,先呈現頁面基本結構。
2.實現方法:
1.在頁面元素后面增加一個骨架div,當頁面加載完成后就隱藏這個div
2.在頁面元素結構中先嵌入骨架div,當頁面加載完成后就替換這個div
3.通過偽元素實現骨架樣式,通過操作樣式實現骨架和頁面的動態切換
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>骨架屏示例</title> <style> *{ margin: 0; padding: 0; } @keyframes loading { 0% { background-position: -400px 0 } 100% { background-position: 400px 0 } } .box1 { position: absolute; margin: 0 auto; left: 50%; margin-left: -400px; top: 0; width: 800px; height: 60px; background-color: blue; background-image: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);//圖像線性漸變寫法 animation-duration: 1s; animation-iteration-count: infinite; animation-name: loading; animation-timing-function: linear; transition: 0.3s; } .bgMasker { background-color: #fff; } .line1 { background-color: #fff; height: 20px; position: absolute; right: 0; top: 0; left: 60px; } .line2 { background-color: #fff; height: 20px; position: absolute; right: 700px; top: 20px; left: 60px; } .line3 { background-color: #fff; height: 20px; position: absolute; left: 400px; right: 0; top: 20px; } .line4 { background-color: #fff; height: 20px; top: 40px; position: absolute; left: 60px; right: 500px; } .line5 { background-color: #fff; height: 20px; position: absolute; left: 600px; right: 0; top: 40px; } </style> </head> <body> <!-- 骨架 --> <div class="box1"> <div class="bgMasker line1"></div> <div class="bgMasker line2"></div> <div class="bgMasker line3"></div> <div class="bgMasker line4"></div> <div class="bgMasker line5"></div> </div> </body> </html>
優點:
簡單,不需要工程,不用puppeteer生成骨架dom,也不需要二次開發維護
定制程度高,想怎么搞就怎么搞
不臃腫,只給你想要的
缺點:
自動化程度低,需要在骨架dom上手動添加類
協同要求高,不像工程化能通過工程去約束
3.優缺點:
優點:
讓應用程序感覺更有表現力,吸引更多的注意力。
內容還在加載中,用戶也可以自由地滾動並與應用程序交互。
缺點:
增加程序運行負擔,無法根本解決頁面加載性能問題。
開發工作量大,對特定頁面數據額外繪制動畫效果。