1# Loading Pages
2
3
4Page loading is a basic function of the [Web](../reference/apis-arkweb/ts-basic-components-web.md#web) component. Depending on the data source, page loading falls into three types: loading of network pages, loading of local pages, and loading of HTML rich text data.
5
6
7If acquisition of network resources is involved in page loading, you need to declare the [ohos.permission.INTERNET](../security/AccessToken/declare-permissions.md) permission.
8
9
10## Loading Network Pages
11
12You can specify the default network page to be loaded when creating a **Web** component. After the default network page is loaded, call [loadUrl()](../reference/apis-arkweb/js-apis-webview.md#loadurl) if you want to change the network page displayed by the **Web** component. The value of the first parameter **src** of the **Web** component cannot be dynamically changed through a state variable (for example, @State). To change the value, call [loadUrl()](../reference/apis-arkweb/js-apis-webview.md#loadurl).
13
14
15In the following example, after the **www.\example.com** page is loaded by the **Web** component, **loadUrl** is called to change the displayed page to **www\.example1.com**.
16
17
18
19```ts
20// xxx.ets
21import { webview } from '@kit.ArkWeb';
22import { BusinessError } from '@kit.BasicServicesKit';
23
24@Entry
25@Component
26struct WebComponent {
27  controller: webview.WebviewController = new webview.WebviewController();
28
29  build() {
30    Column() {
31      Button('loadUrl')
32        .onClick(() => {
33          try {
34            // Upon button clicking, call loadUrl to redirect to www.example1.com.
35            this.controller.loadUrl('www.example1.com');
36          } catch (error) {
37            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
38          }
39        })
40      // When creating a Web component, set the default network page to be loaded to www.example.com.
41      Web({ src: 'www.example.com', controller: this.controller })
42    }
43  }
44}
45```
46
47
48## Loading Local Pages
49
50Local page files are stored in the application's **rawfile** directory. You can specify the local page to be loaded by default when creating a **Web** component. After page loading is complete, you can call [loadUrl()](../reference/apis-arkweb/js-apis-webview.md#loadurl) to change the displayed page of the **Web** component.
51
52
53The following example shows how to load a local page file.
54
55
56- Local page file in the application's resources/rawfile directory:
57
58    **Figure 1** Path of local page files 
59
60    ![resource-path](figures/resource-path.png)
61
62
63- Application code:
64
65  ```ts
66  // xxx.ets
67  import { webview } from '@kit.ArkWeb';
68  import { BusinessError } from '@kit.BasicServicesKit';
69
70  @Entry
71  @Component
72  struct WebComponent {
73    controller: webview.WebviewController = new webview.WebviewController();
74
75    build() {
76      Column() {
77        Button('loadUrl')
78          .onClick(() => {
79            try {
80              // Upon button clicking, call loadUrl to redirect to local1.html.
81              this.controller.loadUrl($rawfile("local1.html"));
82            } catch (error) {
83              console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
84            }
85          })
86        // When creating a Web component, load the local.html file through $rawfile.
87        Web({ src: $rawfile("local.html"), controller: this.controller })
88      }
89    }
90  }
91  ```
92
93
94- Code of the **local.html** page:
95
96  ```html
97  <!-- local.html -->
98  <!DOCTYPE html>
99  <html>
100    <body>
101      <p>Hello World</p>
102    </body>
103  </html>
104  ```
105
106- Code of the **local1.html** page:
107
108  ```html
109  <!-- local1.html -->
110  <!DOCTYPE html>
111  <html>
112    <body>
113      <p>This is local1 page</p>
114    </body>
115  </html>
116  ```
117
118
119## Loading HTML Rich Text Data
120
121The **Web** component provides the [loadData()](../reference/apis-arkweb/js-apis-webview.md#loaddata) API for you to load HTML rich text data. This API is applicable if you want to display some page sections instead of the entire page.
122
123
124
125```ts
126// xxx.ets
127import { webview } from '@kit.ArkWeb';
128import { BusinessError } from '@kit.BasicServicesKit';
129
130@Entry
131@Component
132struct WebComponent {
133  controller: webview.WebviewController = new webview.WebviewController();
134
135  build() {
136    Column() {
137      Button('loadData')
138        .onClick(() => {
139          try {
140            // Upon button clicking, call loadData to load HTML rich text data.
141            this.controller.loadData(
142              "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
143              "text/html",
144              "UTF-8"
145            );
146          } catch (error) {
147            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
148          }
149        })
150      // When creating a Web component, set the default network page to be loaded to www.example.com.
151      Web({ src: 'www.example.com', controller: this.controller })
152    }
153  }
154}
155```
156
157## Dynamically Creating Web Components
158**Web** components can be created with commands. Components created in this mode are not immediately mounted to the component tree, that is, they are not presented to users (their state is **Hidden** or **InActive**). You can dynamically mount the components as required in subsequent use. It is recommended that the number of **Web** instances started in the background be less than or equal to 200. 
159
160```ts
161// Carrier ability
162// EntryAbility.ets
163import { createNWeb } from "../pages/common"
164onWindowStageCreate(windowStage: window.WindowStage): void {
165  windowStage.loadContent('pages/Index', (err, data) => {
166    // Dynamically create a Web component (UIContext needs to be passed in). The component can be created at any time after loadContent is called.
167    createNWeb("https://www.example.com", windowStage.getMainWindowSync().getUIContext());
168    if (err.code) {
169      return;
170    }
171  });
172}
173```
174```ts
175// Create a NodeController instance.
176// common.ets
177import { UIContext, NodeController, BuilderNode, Size, FrameNode } from '@kit.ArkUI';
178import { webview } from '@kit.ArkWeb';
179
180// @Builder contains the specific content of the dynamically created component.
181// Data is an input parameter of encapsulation class.
182class Data{
183  url: string = "https://www.example.com";
184  controller: WebviewController = new webview.WebviewController();
185}
186
187@Builder
188function WebBuilder(data:Data) {
189  Column() {
190    Web({ src: data.url, controller: data.controller })
191      .width("100%")
192      .height("100%")
193  }
194}
195
196let wrap = wrapBuilder<Data[]>(WebBuilder);
197
198// NodeController is used to control and feed back the behavior of the corresponding node in the NodeContainer. It must be used together with NodeContainer.
199export class myNodeController extends NodeController {
200  private rootnode: BuilderNode<Data[]> | null = null;
201  // This function must be overridden. It is used to build the number of nodes and return the number of nodes mounted to the corresponding NodeContainer.
202  // Call it when the NodeContainer is created or call rebuild() to refresh.
203  makeNode(uiContext: UIContext): FrameNode | null {
204    console.log(" uicontext is undefined : "+ (uiContext === undefined));
205    if (this.rootnode != null) {
206      // Return the FrameNode.
207      return this.rootnode.getFrameNode();
208    }
209    // Return null to detach the dynamic component from the bound node.
210    return null;
211  }
212  // Called when the layout size changes.
213  aboutToResize(size: Size) {
214    console.log("aboutToResize width : " + size.width  +  " height : " + size.height );
215  }
216
217  // Called when the NodeContainer bound to the controller is about to appear.
218  aboutToAppear() {
219    console.log("aboutToAppear");
220  }
221
222  // Called when the NodeContainer bound to the controller is about to disappear.
223  aboutToDisappear() {
224    console.log("aboutToDisappear");
225  }
226
227  // This function is a custom function and can be used as an initialization function.
228  // Initialize BuilderNode through UIContext, and then initialize the content in @Builder through the build API in BuilderNode.
229  initWeb(url:string, uiContext:UIContext, control:WebviewController) {
230    if(this.rootnode != null)
231    {
232      return;
233    }
234    // Create a node. UIContext is required.
235    this.rootnode = new BuilderNode(uiContext);
236    // Create a dynamic Web component.
237    this.rootnode.build(wrap, { url:url, controller:control });
238  }
239}
240// Create a map to save the required NodeController.
241let NodeMap:Map<string, myNodeController | undefined> = new Map();
242// Create a map to save the required WebViewController.
243let controllerMap:Map<string, WebviewController | undefined> = new Map();
244
245// UIContext is required for initialization and needs to be obtained from the ability.
246export const createNWeb = (url: string, uiContext: UIContext) => {
247  // Create a NodeController instance.
248  let baseNode = new myNodeController();
249  let controller = new webview.WebviewController() ;
250  // Initialize the custom Web component.
251  baseNode.initWeb(url, uiContext, controller);
252  controllerMap.set(url, controller)
253  NodeMap.set(url, baseNode);
254}
255// Customize the API for obtaining the NodeController.
256export const getNWeb = (url : string) : myNodeController | undefined => {
257  return NodeMap.get(url);
258}
259```
260```ts
261// Use the Page page of the NodeController.
262// Index.ets
263import { getNWeb } from "./common"
264@Entry
265@Component
266struct Index {
267  build() {
268    Row() {
269      Column() {
270        // NodeContainer is used to bind to the NodeController. A rebuild call triggers makeNode.
271        // The Page page is bound to the NodeController through the NodeContainer API to display the dynamic component.
272        NodeContainer(getNWeb("https://www.example.com"))
273          .height("90%")
274          .width("100%")
275      }
276      .width('100%')
277    }
278    .height('100%')
279  }
280}
281
282```
283## Samples
284
285The following samples are provided to help you better understand how to develop the **Web** component:
286
287- [Browser (ArkTS) (Full SDK) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser)
288