Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Promise API to load JS, CSS, or image files

Shulou Source: shulou.com Published: 2022-06-02 22:21:28 09月30日 Update

This article focuses on "how to use Promise API to load JS, CSS or image files". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to load JS, CSS or image files using Promise API.

The easiest way to load resources (JavaScript,CSS, images) using JavaScript or TypeScript.

Web applications typically use third-party API to provide functionality on application-specific routes, many of which are onerous and do not have software packages on NPM. The usual way to add these API to Web applications is to add them to the main HTML file, which can greatly affect page load time. For example, if it is a JavaScript file, it will download, compile, and execute the script.

What if we could avoid loading these API when the page was first loaded? This will help load page content faster, reduce the use of overall network data, and reduce memory usage on low-end devices.

Loadx API

Loadx API will help us load resources asynchronously through the following features:

Load JS,CSS or image

Cache result

⏳️has implemented Promise and async/await brilliantly

️compressed ES3 is only 400byte

Let's use this API to create an example:

Import loadx from 'loadx'; async function getUser () {/ / load Axios API await loadx.js (' https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js'); / / get user return axios.get ('/ user/12345') from Rest API;} async function loadImage (url) {/ / Image container 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'; / / load image await loadx.img (url, containerEl); / / hide the spinner spinnerEl.style.diplay = 'none' } function loadCSSFramework () {/ / simply load Tailwind CSS loadx.css ('https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css');}) so far, I believe you have a better understanding of "how to use Promise API to load JS, CSS or image files". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Images files methods content applications programs pages applications functions resources learning practical deeper heavy low-end interest memory bytes practicality reality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Information OPPO Reno Shulou Tech Info NVidia