Home > Web Front-end > JS Tutorial > body text

Make your web page faster

Susan Sarandon
Release: 2024-09-24 08:30:36
Original
169 people have browsed it

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!