JavaScript bundle DOM Webpack

Just to make it sure:

I am creating a JS bundle using webpack. So far so good. I have different JS files all over, for the different pages, let's say:

  • dashboard
  • users
  • etc.

I access the DOM in let's say dashboard doing document.getElementById('id-rocks').

My question is, if I open a different page that doesn't have that element on the page, this will throw of course an error because it has the whole beautiful bundle with all the JS for all the pages / components.

I just want to know if this is really a downside from creating bundles, and the only viable solution is to just check on that JS file if the element is existing or not with an if condition.

const el = document.getElementById('id-rocks');

if (el) {
// Page logic
}

This may sound silly, but I want to know if there are alternatives...

Of course, I could go and put every file on every page, what's needed, but it is not my idea, I want to have module dependency, ES6 imports and stuff. What I would maybe investigate is code splitting, etc. But this has nothing to do with the matter of this question.

Another off topic I would like to mention: HTTP2 and multiplexing, is it a good idea to start thinking about NOT bundling the whole thing just because soon the HTTP requests will not be a problem any more?

Thanks in advance.