Why "Domcontentloaded" only works after Ctrl+F5

Asked

Viewed 220 times

1

I have some problems with document.addEventListener("DOMContentLoaded" in the following section. I can only get the values of list when I activate the Ctrl+F5. I need to have it when first loaded. I can use onload in Istener? Thank you.

document.addEventListener("DOMContentLoaded", function(e) {
                    console.log('state2',document.readyState);

                var list = document.getElementsByClassName( 'morph-button1' );
                console.log('list',list.length);

                var i;

                    for(i=0; i < list.length; i++){
                        console.log('list iteration', list);
                        console.log('list index', i);
                        new UIMorphingButton( list[i], {
                            closeEl : '.icon-close',
                            onBeforeOpen : function() {
                                // don't allow to scroll
                                noScroll();
                            },
                            onAfterOpen : function() {
                                // can scroll again
                                canScroll();
                                console.log(list[i]);
                            },
                            onBeforeClose : function() {
                                // don't allow to scroll
                                noScroll();
                            },
                            onAfterClose : function() {
                                // can scroll again
                                canScroll();
                            }
                        } );

                    }
                });

3 answers

4

Domcontentloaded is an event triggered as soon as the HTML is loaded. It is possible that the event will fire even before your Javascript is loaded. If this happens, when your Event Listener is loaded, it will not run as it could not capture the event when it was fired.

In this case, you can double-check. When your Javascript loads, make sure the HTML is already loaded. If yes, fire your function, if not, create your Event.

if (document.readyState === "loading")
    document.addEventListener("DOMContentLoaded", onDOMLoaded);
else 
    onDOMLoaded();


function onDOMLoaded() {
    console.log('state2', document.readyState);

    var list = document.getElementsByClassName('morph-button1');
    console.log('list', list.length);

    var i;

    for (i = 0; i < list.length; i++) {
        console.log('list iteration', list);
        console.log('list index', i);
        new UIMorphingButton(list[i], {
            closeEl: '.icon-close',
            onBeforeOpen: function () {
                // don't allow to scroll
                noScroll();
            },
            onAfterOpen: function () {
                // can scroll again
                canScroll();
                console.log(list[i]);
            },
            onBeforeClose: function () {
                // don't allow to scroll
                noScroll();
            },
            onAfterClose: function () {
                // can scroll again
                canScroll();
            }
        });

    }
}
  • opa, this occurs even in the html elements being created in Document? because the query and view comes from the database all by javascript.

3

Use the event function readystatechange and execute the code only when the return of the event is equal to complete (means the page has been fully loaded, including asynchronous items such as images and scripts).

If you use document.readyState outside the event readystatechange, the result will always be loading (loading). Using within the event DOMContentLoaded, the result will be interactive (the DOM was loaded, but asynchronous items were not).

document.onreadystatechange = function(){

   if(document.readyState == "complete"){

      console.log('state2',document.readyState);

      var list = document.getElementsByClassName( 'morph-button1' );
      console.log('list',list.length);

      var i;

      for(i=0; i < list.length; i++){
         console.log('list iteration', list);
         console.log('list index', i);
         new UIMorphingButton( list[i], {
            closeEl : '.icon-close',
            onBeforeOpen : function() {
               // don't allow to scroll
               noScroll();
            },
            onAfterOpen : function() {
               // can scroll again
               canScroll();
               console.log(list[i]);
            },
            onBeforeClose : function() {
               // don't allow to scroll
               noScroll();
            },
            onAfterClose : function() {
               // can scroll again
               canScroll();
            }
         });
      }
   }

}

0

Solved, I added a note and managed to keep the loop, the problem was in loading the list, var list = document.getElementsByClassName( 'morph-button1' );

Follow the example of how it turned out.

function click() {          
        console.log('teste de documento',document.querySelectorAll( '.morph-button' ));
        var len = document.getElementsByClassName( 'morph-button' );
        console.log('teste de documento', len.length);

        var nodes = document.querySelectorAll( '.morph-button' );
            var docElem = window.document.documentElement, didScroll, scrollPosition;


            function noScrollFn() {
                window.scrollTo( scrollPosition ? scrollPosition.x : 0, scrollPosition ? scrollPosition.y : 0 );
            }

            function noScroll() {
                window.removeEventListener( 'scroll', scrollHandler );
                window.addEventListener( 'scroll', noScrollFn );

            }

            function scrollFn() {
                window.addEventListener( 'scroll', scrollHandler );
            }

            function canScroll() {
                window.removeEventListener( 'scroll', noScrollFn );
                scrollFn();
            }

            function scrollHandler() {
                if( !didScroll ) {
                    didScroll = true;
                    setTimeout( function() { scrollPage(); }, 60 );
                }
            };

            function scrollPage() {
                scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
                didScroll = false;
            };

            scrollFn();


            console.log('this', this.target);
            console.log('state2', document.readyState);



            var divArray = document.getElementById('atividades');

            var observer = new MutationObserver(function(){
               console.log('observer1', document.getElementsByClassName('morph-button').length);
               console.log('observer2',document.getElementsByClassName('morph-button'));

               var list = document.getElementsByClassName('morph-button');
                console.log('list', list.length);

               // var i;

                for (var i = 0; i < list.length; i++) {
                    console.log('list iteration', list);
                    console.log('list index', i);

                    new UIMorphingButton( list[i], {
                        closeEl: '.icon-close',
                        onBeforeOpen: function () {

                            noScroll();

                        },
                        onAfterOpen: function () {

                            canScroll();

                        },
                        onBeforeClose: function () {

                            noScroll();

                        },
                        onAfterClose: function () {

                            canScroll();

                        }
                    });

                }

            });

            observer.observe(divArray, { attributes: false, childList: true, subtree: true });

            // When you've got what you need, you should call this function to trigger a disconnect 
            function classesFound(){
               observer.disconnect();
            };

}

window.onload = click;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.