Wait for document ready in ES6 modules

DOM has not changed in ES6, ES6 gives new features to JavaScript, that is all. In pure js exists event for dom loaded ( it is document ready from jquery equivalent ):

document.addEventListener("DOMContentLoaded",function(){

    //Your code here
});

Modules working with DOM tree can have listener inside, or should be used after dom is ready. I created example DomManipulate component to show what I mean:

var DomManipulate=function(selector){

   document.addEventListener("DOMContentLoaded",()=>{

      this.element=document.querySelector(selector);

      if (typeof this.callback === 'function')
      this.callback();

   });

};

//HERE WE HAVE CALLBACK WHEN OUR MODULE CAN BE USED
DomManipulate.prototype.onReady=function(callback){

    this.callback=callback;

};

DomManipulate.prototype.getElement=function(){
    //example object method

   return this.element;

};

DomManipulate.prototype.write=function(text){

   return this.element.innerText=text;

};


export { DomManipulate };

So it is better approach and we have encapsulated component.

Usage example:

var d=new DomManipulate("#test");
d.onReady(()=>{d.write("Test text");});

Modules should be DOM independent, creating modules which are exporting DOM elements directly are very wrong practice. So it can be done in two ways:

  1. Modules should get selectors DOM object in attributes and should be called after DOM is ready. So Your module has no idea where is called, but it needs ready DOM structure. In this situation DOM ready callback is only in main file which is using modules and call them.

  2. Modules can have some DOM ready listeners but also We need some information when module can be used ( this situation I showed in example and onReady function).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)