Add loading effect to iframe

Problem: When a page embeds an iframe, there is a delay in iframe loading. That is, before the iframe element is displayed, the parent page embedded in the iframe will have a blank screen for a while, and the user cannot perceive that the iframe page is loading, and the experience effect is not very good.

Solution: In order to improve the user experience and let the user perceive that the current page is loading the iframe, add a loading effect before the iframe is loaded to replace the original white screen. The style is roughly as shown in the figure below. You can refer to the loading effect in element ui, Loading components .

Specific code implementation: The technology stack used is vue3+composition api, the @load event in the iframe is triggered after the iframe page is loaded, that is, the handleIframeLoad function as follows.

 <div class="iframe-wrap">
    <loading v-if="isLoading"></loading>
    <iframe
        ref="iframeRef"
        class="iframe-wrap__iframe"
        allow="clipboard-read; clipboard-write"
        :src="iframeSrc"
        @load="handleIframeLoad"
    ></iframe>
</div>

Control whether the Loading icon is displayed by changing the isLoading variable. Initialize and define the variable isLoading to be true. When the iframe is loaded, set the variable isLoading to false, and set the variable isLoading to true again in the page closing function. details as follows:

const isLoading = ref(true);
function handleIframeLoad() {
    isLoading.value = false;
}
function close() {
    isLoading.value = true;
}

Guess you like

Origin blog.csdn.net/lfq1996/article/details/129524003