search
HomeWeb Front-endJS TutorialMake your web page faster

Make your web page faster

What is a DOM? What does it eat?

The DOM (Document Object Model) is the base of web pages and developing them. It's a programming interface for HTML and XML documents, representing the structure of a document in a tree-like object. With branches and leaves. Each element, attribute, and piece of text in the document becomes a node in this tree. It allows JavaScript to interact with HTML elements, modify them or add new elements. This is a rough digest of what every person experiences on the web, interaction, mutability, dynamic visual cues and elements. When you click a button or a shiny menu, your brain expects something to happen. To a sentence to change, to a new be page to be loaded or to a popup with a green check mark telling us that our online order was paid successfully.

Manipulating the DOM too fast, every second, is a big no-no for user retention or even basic interaction from the user. Even with all the dynamic behavior we can create and expand the user experience, the over usage of DOM manipulations can be very frustrating. And the final saying is always from the user. If you have crucial operations happening in the background of your page, like data fetching, but the performance just tanks and becomes worse by the minute after the user interacts with it, it can be very hard and daunting to pinpoint the choke points.

A example of simple way of using the basic way of doing things and doing it faster, is using textContent from vanilla js. Yes, I know. Most of the time we need a complex cycle of life for components that are so dynamic and mutable that we need to use state management and such. But that is not always the case. If you are only changing some text or updating a cookie once per session, do you really need to use such a complex logic and resource hungry option?

The textContent function is the fastest in js for manipulating text when compared with similar functionality options, for example, the more popular innerHtml method. See these timed tests for reference.

Why?

You can save up the user's machine memory for other way more impactful operations. Sometimes being accessible and reasonably fast in really old android or apple devices, for example, is a must. Or maybe your API call returns a JSON so big that you need a couple of seconds for parsing and proper manipulation. So every second that the user gets no feedback or is stuck watching a CSS animation on screen, counts.

I learned a lot recently was by coding in JavaScript with no dependencies, as a challenge and learning experience. Like fetching data and creating a to do app with just HTML, CSS and JavaScript. No npm, no libraries. And I found out a bunch of Web API's method and objects I never heard of before, like the DocumentFragment object. It creates a empty 'fragment' of a DOM structure and let's you manipulate it and populate it before actually changing the page's DOM. So you load up a object with your list of menus or your super fancy AI powered tool's titles, and after you are done with the appending operations and nesting tags, you patch it to the DOM once. In such way that the parsing only happens once, in one go, instead of doing a for loop with many identical calls, and requiring a new parsing of the tree at the end of every call.

So lets say I click a button really fast, because my use case requires rendering really fast, more than 1 time a second. Using your favorite state management library can create some sort of barrier in this case, because after every click there was new event fired, so it must go off before starting the second instance of the event in the stack, by default. Depending on the complexity or the need of a async operation, that can take more than a second. In this use case, is a deal breaker. So, choosing the right tool can be simpler, shorter and even faster. Nowadays there are options that popular libraries offer to solve this issue, like breaking execution of a re-render when a new identical event fired recently. But my point here is, not to just pursue a pretty and modern looking web application. But to make your own life easier by making maintenance the easiest you can and not shoot yourself on the foot by blindly trusting chunks of code that someone wrote and says that is the best option.

If you are already installing these packages and libraries to fire up your project, why not investigate why errors and exceptions spit out unknown function calls or cryptic messages on the console?

Conclusion et quelques divagations supplémentaires

Obtenir gratuitement un service opérationnel sur le cloud ou dans un service très courant peut être très rapide et si simple de nos jours. Utiliser une plaque passe-partout comme point de départ peut être très utile et vous fera gagner du temps sans vous soucier des tâches très basiques et récurrentes. Tapez simplement une seule commande dans votre terminal et voilà, le routage de base et une page hello world fonctionnant sur un serveur local.

Personne, nulle part sur Internet, ne saura toujours ce qu'une bibliothèque déterminée ou un framework entier fait sous le capot, mais plus vous saurez comment les choses fonctionnent, plus souvent vous serez en mesure de prendre des décisions plus éclairées et de travailler efficacement.

Les frameworks les plus populaires pour le développement Web font un excellent travail pour optimiser le rendu et manipuler le DOM en utilisant des ressources comme un DOM virtuel ou implémenter une sorte de persistance pour les opérations très exigeantes qui récupèrent des données.

Les outils de développement Web de votre navigateur Web de choix sont votre meilleur ami ici. Les versions plus récentes de ces outils peuvent vous fournir une télémétrie et même montrer quelle partie de votre code ou quels appels sont le point d'étranglement possible de vos performances.

En sachant comment fonctionne le langage JavaScript ou comment il implémente sa façon de faire, vous pouvez facilement identifier les situations dans lesquelles une fonction prête à l'emploi de votre bibliothèque préférée pourrait vous obliger à créer une base de code plus volumineuse et à ne pas vous concentrer sur la résolution du problème. problème. Cela pourrait simplement attirer votre attention sur la réplication d'un morceau de code que vous avez écrit des centaines de fois. Et même avec l'IA pour augmenter votre productivité, vous pourriez tomber dans le piège d'utiliser une solution suggérée par votre compagnon artificiel, et en réalité rendre les choses plus difficiles à maintenir à l'avenir.

Ne vous inquiétez pas, parfois nous ne savons tout simplement pas mieux. Comme je l'ai dit, personne ne peut tout savoir à tout moment.

Expérimenter et faire des erreurs dans des moments plus indulgents vous aidera beaucoup et vous donnera les outils dont vous avez besoin pour faire mieux. La prochaine fois que vous aurez l'occasion de faire quelque chose d'aussi simple que déployer un serveur de fichiers statique ou coder une logique très complexe pour un cas d'utilisation très spécialisé, connaître les bases vous mènera très loin et vous donnera plus de clarté face à de nouveaux problèmes dans votre carrière.

Je vous recommande fortement de consulter la documentation de l'API Web. En plus de jeter un œil aux blogs en ligne, aux réseaux sociaux ou aux ressources axées sur le développement Web.

Si j'ai fait des erreurs, ce qui est probable, n'hésitez pas à me le faire savoir dans les commentaires. Je suis à l'écoute des critiques et des nouvelles idées, alors s'il vous plaît, partagez-les si vous le souhaitez !

The above is the detailed content of Make your web page faster. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

Load Box Content Dynamically using AJAXLoad Box Content Dynamically using AJAXMar 06, 2025 am 01:07 AM

This tutorial demonstrates creating dynamic page boxes loaded via AJAX, enabling instant refresh without full page reloads. It leverages jQuery and JavaScript. Think of it as a custom Facebook-style content box loader. Key Concepts: AJAX and jQuery

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How to Write a Cookie-less Session Library for JavaScriptHow to Write a Cookie-less Session Library for JavaScriptMar 06, 2025 am 01:18 AM

This JavaScript library leverages the window.name property to manage session data without relying on cookies. It offers a robust solution for storing and retrieving session variables across browsers. The library provides three core methods: Session

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.