Piotr Nowak
Piotr Nowak

Reputation: 39

A lot of divs on one page

Is there any way to "unrender" elements which aren't visible on screen?
I have a page with a lot divs, some of them have event listeners attached to them. Above 45k divs event handlers are running very slow, so I thought maybe unrendering unnecessary element would help?

FYI - when elements have display: none everything works fine.

Upvotes: 0

Views: 176

Answers (2)

TryingToImprove
TryingToImprove

Reputation: 7407

Instead of adding 45k of event listeners, you should add one event listener on a parent-div.

With jQuery you can do something like this:

<div id="container">
  <div class="clickable">a</div>
  <div class="clickable">a</div>
  <div class="clickable">a</div>
  <div class="clickable">a</div>
  <div class="clickable">a</div>
  <div class="clickable">a</div>
  <div class="clickable">a</div>
  <div class="clickable">a</div>
</div>

.

$("#container").on('click', '.clickable', function(e) {
  console.log($(e.target));
})

this should improve your javascript code.

If you still need to hide elements who a not visible you will need to calculate their positions, and that might decrease your performence

Upvotes: 2

Neo
Neo

Reputation: 3399

Use divs when you need to divide (that's what divs are supposed to be used for) sections of your page from one another. Header/footer from content for instance, or individual posts on a blog.

However, you shouldn't use them when semantically where another element would make sense. While this is not a duplicate, I think the info found here will be of use to you. Too Many DIVS?

Upvotes: 0

Related Questions