如何在从 API 获取数据时添加加载动画?香草js

How to add a loading animation while Fetch data from API? Vanilla js

我在这里尝试了很多答案,但我找到的所有答案,人们都在使用 jquery、ajax、react 或类似的东西。我想要纯 javascript (vanilla js) 的答案。

const movieApiMovies = () => {
fetch(movieApi_url + "movies/")
    .then(response => response.json())
    .then(function (data) {
        let result = `<h2> Movies I've watched! </h2>`;
        data.forEach((movie) => {
            const {id, name, year, note_imdb, genre, duration} = movie;
            result +=
                `<div>
                    <h5> Movie ID: ${id} </h5>
                    <ul>
                        <li>Movie name: ${name}</li>
                        <li>Movie year: ${year}</li>
                        <li>Movie note on IMDB: ${note_imdb}</li>
                        <li>Movie Genre: ${genre}</li>
                        <li>Movie duration: ${duration}</li>
                    </ul>
                </div>`;
            document.getElementById('movieResult').innerHTML = result;
        })
    })
};

我有一个动画,它在这个 Div 元素上。

<div class="boxLoading"></div>

我有一个可以调用所有内容的按钮。

<div id="button1">
      <button class="button" id="moviesfromapi"onclick="movieApiMovies ()">Display</button>
</div>

在调用之前添加加载程序,并在收到结果后删除,如下所示

const movieApiMovies = () => {
let loader = `<div class="boxLoading"></div>`;
document.getElementById('movieResult').innerHTML = loader;
fetch(movieApi_url + "movies/")
    .then(response => response.json())
    .then(function (data) {
        let result = `<h2> Movies I've watched! </h2>`;
        data.forEach((movie) => {
            const {id, name, year, note_imdb, genre, duration} = movie;
            result +=
                `<div>
                    <h5> Movie ID: ${id} </h5>
                    <ul>
                        <li>Movie name: ${name}</li>
                        <li>Movie year: ${year}</li>
                        <li>Movie note on IMDB: ${note_imdb}</li>
                        <li>Movie Genre: ${genre}</li>
                        <li>Movie duration: ${duration}</li>
                    </ul>
                </div>`;
            document.getElementById('movieResult').innerHTML = result;
        })
    })
};