1
votes

I made a small website with Bootstrap 4.3.1, and require no javascript for it except the collapse plugin for the responsive navbar with a toggler button.

There is no customizer anymore for Bootstrap 4, so I'm forced to load jquery-3.3.1.slim.min.js with 69 kiB, and bootstrap.min.js with 57 kiB, which results in a download of 126 kiB Javascript for an interactive menu toggle button on small screens.

Is there anything I can do to decrease the javascript download size for my users?

1

1 Answers

2
votes

Remove all the jQuery and bootstrap javascript, and add this:

  <script type="text/javascript">
   const triggers = Array.from(document.querySelectorAll('[data-toggle="collapse"]'));
   triggers.forEach(elem => {
       elem.addEventListener('click', event => {
           const selector = elem.getAttribute('data-target');
           collapse(selector, 'toggle');
       });
   });

   const fnmap = {
       'toggle': 'toggle',
       'show': 'add',
       'hide': 'remove'
   };

   const collapse = (selector, cmd) => {
       const targets = Array.from(document.querySelectorAll(selector));
       targets.forEach(target => {
           target.classList[fnmap[cmd]]('show');
       });
   };
  </script>

Inspired by https://medium.com/dailyjs/mimicking-bootstraps-collapse-with-vanilla-javascript-b3bb389040e7