📜 ⬆️ ⬇️

A simple way to slightly unload initialization javascript on the page

Perhaps someone would benefit from such an idea.


You have a large multipage website. On different pages you have different complex javascript things: beautiful galleries, Ajax leaflets, somewhere in general almost an application is made. All this is rotated on some jQuery / Prototype / Mootools / etc., For each such piece a bunch of functions, complex selectors of IDs and classes, etc. are called. etc.
And all of these scripts you, as a developer who cares about performance, neatly stuffed it into one JS file and packed it.

But there is a nuisance: when you open each page, your script will coat the DOM, in an attempt to find and select all the nodes that are involved in all the above “pieces”. Those. how many selectors you have in a script like $('.myclass') , getElementById , etc., so many times after loading the DOM it will be scanned in search of these elements.

And if you have a script for 1.5 thousand lines and such selectors you have "over 9000"? This will slow down the page loading. Of course, the losses are not so big to somehow bother much, but you can get rid of it very simply and easily: wrap up sets of functions describing the work of JS applications in checking the availability of these same applications.

That is, if you have an application on a page, then it sits in some <div id="my_app">...</div> .
Wrap all the functions that describe the operation of this application in this design:
  if (document.getElementById ('my_app')) {
	 // code here			 
 } 

and, if there is no node on the page with id="my_app" , then the parser will pass by and will not try to find on the page everything that is called relative to the application.
')
Trifle, but nice

Source: https://habr.com/ru/post/101431/


All Articles