Search code examples
javascriptlazy-loadingbootstrap-native

After lazy loading the Bootstrap Javascript, how to trigger it's initCallback function?


Since the Bootstrap-native javascript isn't directly necessary as it only really is needed when the user starts interacting with the page, I figure I can lazy load it. (Yea ok it's only a few KB, but hey if it's possible, why not?)

The minor problem is that the bootstrap script will trigger it's initalization function initCallback() on the DOMContentLoaded event. this function, I believe, will look for the data tags in the HTML and associate appropriate events/triggers. Since it's being lazy loaded, DOMContentLoaded fires before the bootstrap.js is downloaded and thus it's missing this event and does not initialize.

I'm just a hobbyist in Javascript; and I can't seem to figure out how to manually call this function after fetch() (actually using a function i found on the net called fetchInject() ) has completed downloading the script.

Maybe lazy loading bootstrap isn't a good idea; but I will figure that out in the long run I guess; if I get this to work at least.

  /* Native Javascript for Bootstrap 4 | Initialize Data API
  --------------------------------------------------------*/
  var initializeDataAPI = function( constructor, collection ){
      for (var i=0, l=collection[length]; i<l; i++) {
        new constructor(collection[i]);
      }
    },
    initCallback = BSN.initCallback = function(lookUp){
      lookUp = lookUp || DOC;
      for (var i=0, l=supports[length]; i<l; i++) {
        initializeDataAPI( supports[i][1], lookUp[querySelectorAll] (supports[i][2]) );
      }
    };

  // bulk initialize all components
  DOC[body] ? initCallback() : on( DOC, 'DOMContentLoaded', function(){ initCallback(); } );

initCallback() to execute, so that bootstrap will find all the HTML inline data hooks (like the dropdowns and stuff)


Solution

  • Have you tried accessing global bootstrap namespace like just running this code:

    BSN.initCallback();