使用Promise API加載JS、CSS或圖像文件
使用JavaScript或TypeScript加載資源(JavaScript,CSS,圖像)的最簡單方法。
Web應(yīng)用程序通常使用第三方API在應(yīng)用程序的特定路由上提供功能,其中許多API都很繁重,并且NPM上沒有軟件包。在Web應(yīng)用程序上添加這些API的通常方法是將其添加到主HTML文件中,使用這種方法會大大影響頁面加載時間。例如,如果是JavaScript文件,它將下載,編譯并執(zhí)行腳本。
如果我們可以避免在頁面首次加載時加載這些API會怎樣呢?這將有助于更快地加載頁面內(nèi)容,減少總體網(wǎng)絡(luò)數(shù)據(jù)的使用,并降低低端設(shè)備的內(nèi)存使用。
Loadx API
Loadx API將通過以下功能幫助我們異步加載資源:
- 加載JS,CSS或圖像
- 緩存結(jié)果
- ⏳️出色地實現(xiàn)了Promise和async/await
- ️壓縮后的ES3僅400字節(jié)
讓我們使用此API創(chuàng)建一個示例:
- import loadx from 'loadx';
- async function getUser() { // 加載Axios API
- await loadx.js('https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js');
- // 從Rest API獲取用戶
- return axios.get('/user/12345');
- }async function loadImage(url) { // 圖像容器
- const containerEl = document.querySelector('.container');
- // loading spinner
- const spinnerEl = document.querySelector('.spinner');
- if (containerEl === null || spinnerEl === null) {
- throw new Error('Image container not found')
- } // show the spinner
- spinnerEl.style.diplay = 'block';
- // 加載圖像
- await loadx.img(url, containerEl);
- // hide the spinner
- spinnerEl.style.diplay = 'none';
- }function loadCSSFramework() { // 簡單加載Tailwind CSS
- loadx.css('https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css');
- }
結(jié)束
現(xiàn)在,只有在需要時才可以加載資源。試一試吧!