html tag run only after whole page is loaded

Why does HTML tag run only after the whole page is loaded?

HTML tags are basically used to define content and structure of a webpage. They are responsible for displaying the data in a user-friendly manner. But have you ever noticed that your web page doesn't load the content until the entire page is loaded? This happens because the browser renders the HTML tags in a sequential manner.

How do HTML tags work?

When a web page is opened in a browser, the browser reads the HTML code line by line and generates a Document Object Model (DOM) tree. The DOM tree is a tree-like representation of the HTML code where each tag is represented by a node. The browser analyses the DOM tree and loads the content of the page sequentially from top to bottom.

When the browser encounters an HTML tag, it first checks whether all the resources associated with that tag are loaded or not. If any resource is still loading, then the browser waits for it to complete the loading process before executing the HTML tag. This is why HTML tags run only after the whole page is loaded.

Example of HTML tag


<body>
  <h1>Hello World!</h1>
  <p>This is my first webpage</p>
</body>

In this example, when the browser encounters the <body> tag, it waits for all the associated resources to load before displaying the content inside it. This means that if there are any images or stylesheets inside the <body> tag, the browser will wait for them to load before displaying the <h1> and <p> tags.

Alternative ways to load HTML tags

There are a few alternative ways to load HTML tags on a webpage:

  • Async attribute: You can add the async attribute to the HTML tag to tell the browser that it can continue loading the page while the tag is being executed. This is useful for tags that don't affect the content of the page, like analytics or tracking scripts.
  • Defer attribute: The defer attribute is similar to async, but it tells the browser to execute the tag after the page has finished loading. This is useful for tags that affect the content of the page, like scripts that manipulate the DOM.

Conclusion

In conclusion, HTML tags run only after the whole page is loaded because the browser renders them sequentially and waits for all associated resources to load before executing them. However, async and defer attributes can be used to load tags in a different manner depending on their impact on the content of the page.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe