DEV Community

SameX
SameX

Posted on

ArkWeb Page Preloading and Caching - Enhancing User Experience

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices.
It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together.
This article is original content, and any form of reprint must indicate the source and the original author.

Introduction

In Web application development, the page loading speed and smoothness directly affect the user experience. The ArkWeb framework provides powerful page preloading and caching functions, which can help developers improve the responsiveness and efficiency of applications. This article will introduce in detail how to implement page preloading, resource preloading, set cache modes, and clear caches in the ArkWeb framework, and demonstrate the application of these techniques through abundant code examples.

Page Preloading

Preloading the Upcoming Accessed Page

Preloading pages can reduce the waiting time for users and enhance the continuous experience of the application. In ArkWeb, you can use the prefetchPage method to preload pages.

Web({ src: "https://www.example.com" })
  .onPageEnd(() => {
        // When the current page loading is completed, preload the next page
        this.controller.prefetchPage("https://www.example.com/next-page", {
            mode: 'Preload', // Set the preloading mode
            onProgressChange: (progress) => {
                // Monitor the preloading progress
                console.log(`Preloading progress: ${progress}%`);
            },
            onComplete: () => {
                // The callback function when preloading is completed
                console.log('Preloading completed successfully.');
            },
            onError: (error) => {
                // The callback function when an error occurs during preloading
                console.error('Preloading failed:', error);
            }
        });
    });
Enter fullscreen mode Exit fullscreen mode

Preloading Page Resources

Besides preloading the entire page, you can also preload specific resources such as images, CSS files, or JavaScript files.

Web({ src: "https://www.example.com" })
  .onPageEnd(() => {
        // Preload image resources
        this.controller.prefetchResource({
            url: "https://www.example.com/assets/logo.png",
            method: "GET",
            headers: [{ key: "Content-Type", value: "image/png" }]
        }, {
            mode: 'Preload',
            onProgressChange: (progress) => {
                console.log(`Resource preloading progress: ${progress}%`);
            }
        });
    });
Enter fullscreen mode Exit fullscreen mode

Page Caching

Setting Cache Modes

Reasonably setting cache modes can reduce network requests and accelerate page loading speed. ArkWeb provides multiple cache modes for developers to choose from.

Web({ src: "https://www.example.com" })
  .cacheMode(CacheMode.Default) // Use the default cache mode
  .onCreate(() => {
        // When the Web component is created, the cache policy can be further configured
        this.controller.setCacheMode(CacheMode.Online, (error) => {
            if (error) {
                console.error('Failed to set cache mode:', error);
            } else {
                console.log('Cache mode set to Online successfully.');
            }
        });
    });
Enter fullscreen mode Exit fullscreen mode

Clearing Cache

When the cached data is no longer needed, clearing the cache in a timely manner can release storage space and ensure the performance of the application.

Web({ src: "https://www.example.com" })
  .onPageEnd(() => {
        // Clear all caches
        this.controller.removeCache(true, (error) => {
            if (error) {
                console.error('Failed to remove cache:', error);
            } else {
                console.log('Cache removed successfully.');
            }
        });
    });
Enter fullscreen mode Exit fullscreen mode

Example Code

The following is a complete example showing how to implement page preloading, resource preloading, set cache modes, and clear caches in an ArkWeb application.

import { webview } from '@ohos.web.webview';
import { CacheMode } from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
    controller: webview.WebviewController = new webview.WebviewController();
    build() {
        Column() {
            // Preload the upcoming accessed page
            Web({ src: "https://www.example.com" })
              .onPageEnd(() => {
                    this.controller.prefetchPage("https://www.example.com/next-page", {
                        mode: 'Preload',
                        onProgressChange: (progress) => {
                            console.log(`Preloading progress: ${progress}%`);
                        },
                        onComplete: () => {
                            console.log('Preloading completed successfully.');
                        },
                        onError: (error) => {
                            console.error('Preloading failed:', error);
                        }
                    });
                });
            // Preload page resources
            Web({ src: "https://www.example.com" })
              .onPageEnd(() => {
                    this.controller.pprefetchResource({
                        url: "https://www.example.com/assets/logo.png",
                        method: "GET",
                        headers: [{ key: "Content-Type", value: "image/png" }]
                    }, {
                        mode: 'Preload',
                        onProgressChange: (progress) => {
                            console.log(`Resource preloading progress: ${progress}%`);
                        }
                    });
                });
            // Set cache mode
            Web({ src: "https://www.example.com" })
              .cacheMode(CacheMode.Default)
           .onCreate(() => {
                this.controller.setCacheMode(CacheMode.Online, (error) => {
                    if (error) {
                        console.error('Failed to set cache mode:', error);
                    } else {
                        console.log('Cache mode set to Online successfully.');
                    }
                });
            });
        // Clear cache button
        Button("Clear Cache")
           .width("100%")
           .height(50)
           .onClick(() => {
                this.controller.removeCache(true, (error) => {
                    if (error) {
                        console.error('Failed to remove cache:', error);
                    } else {
                        console.log('Cache removed successfully.');
                    }
                });
            });
    }
}
}
Enter fullscreen mode Exit fullscreen mode

Summary

From the above examples, we can see that the ArkWeb framework provides developers with rich APIs to optimize the performance of Web applications. Reasonably utilizing functions such as page preloading, resource preloading, cache mode setting, and cache clearing can significantly enhance the user experience. In the actual development process, appropriate optimization strategies should be selected according to the actual situation of the application and the needs of users.

Precautions

  • The preloading and caching strategies need to be adjusted according to the actual network situation and user behavior to avoid excessive consumption of users' data traffic and device storage.
  • When clearing the cache, users' usage habits should be considered to avoid frequent clearing that causes users to need to re-download resources.

Top comments (0)