使用Promise API加载JS、CSS或图像文件

使用JavaScript或TypeScript加载资源(JavaScript,使用CSS,加载图像)的图像最简单方法。

Web应用程序通常使用第三方API在应用程序的文件特定路由上提供功能,其中许多API都很繁重,使用并且NPM上没有软件包。加载在Web应用程序上添加这些API的图像通常方法是云服务器提供商将其添加到主HTML文件中,使用这种方法会大大影响页面加载时间。文件例如,使用如果是加载JavaScript文件,它将下载,图像编译并执行脚本。文件

如果我们可以避免在页面首次加载时加载这些API会怎样呢?使用这将有助于更快地加载页面内容,减少总体网络数据的香港云服务器加载使用,并降低低端设备的图像内存使用。

Loadx API

Loadx API将通过以下功能帮助我们异步加载资源:

加载JS,CSS或图像 缓存结果 ⏳️出色地实现了Promise和async/await ️压缩后的ES3仅400字节

让我们使用此API创建一个示例:

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

结束

现在,只有在需要时才可以加载资源。试一试吧!

滇ICP备2023000592号-31