JQuery detach () v / s remove () v / s hide ()

I use highcharts on my page. It's hard.

When the user clicks the button, he dynamically loads the diagrams and when the user clicks the close button, he removes / hides the diagram.

I want to know which one would be the best option.

  • Hiding chart when user clicks? Will it slow down the rest of the page (how heavy javascript is present along with the handlers?) Or

  • remove() so that it makes the page easier (but here, when the user clicks the button again, I need to load the diagrams again) or

  • Use detach() , so when you reload graphic cards it works faster than remove() (but doesn't make it heavier than jQuery handlers are present all the time?)

I know from jQuery docs,

.remove ()

The .remove () method accepts elements from the DOM. Use .remove () when you want to remove the element itself, as well as everything inside It. In addition to the elements themselves, all related events and jQuery Data associated with the elements are deleted.

.detach ()

The .detach () method is the same as .remove (), except that .detach () saves all jQuery data associated with deleted items. This method is useful when deleted items must be reinserted into the DOM at a later time.

.hide ()

Corresponding elements will be immediately hidden without animation. This is roughly equivalent to calling .css ('display', 'none')

+7
source share
2 answers

If you just want to hide / show the object from time to time, use jQuery .hide() and .show() . This is the simplest and as long as you are going to hold the object anyway, you can simply use .hide() and .show() . If an object does not consume huge amounts of memory, this should not be a problem.

.remove() (when saving and reinserting the same object back into the DOM later) will be of little use to you, since it destroys some data associated with the object, so you cannot easily reinsert it on the page.

.remove() , where you actually allow the previous object to be destroyed by the garbage collector and then recreate it again from scratch when necessary, this is the most efficient memory operation, but if it does not consume a lot of memory or you have a lot of them (for example, thousands ), it’s probably just more work to do it this way without any meaningful benefit.

.detach() (while saving and reinserting the same object back into the DOM later) will work, but it works more than .hide() and .show() , and to be honest, I rather doubt that you will find the difference between two parameters.

+5
source

3 will cause rendering and redrawing, therefore, if performance is your problem, switch to .hide (), as it will β€œsave” some manipulations with dom (and, possibly, 2 redraws). Do not forget about the listeners on your schedule.

However, I found that forperformance .addClass('hidden') and .removeClass('hidden') , with the css rule ( .hidden {display: none} ) works best. (until you want to scroll).

+5
source

All Articles