WordPress.org

Make WordPress Core

Ticket #48601: load-touch-detection-when-dom-is-ready.diff

File load-touch-detection-when-dom-is-ready.diff, 2.2 KB (added by Boga86, 3 weeks ago)

Only load the touch detection code when the DOM is ready

  • src/wp-content/themes/twentytwenty/assets/js/index.js

     
    7171
    7272// Add a class to the body for when touch is enabled for browsers that don't support media queries
    7373// for interaction media features. Adapted from <https://codepen.io/Ferie/pen/vQOMmO>
    74 ( function() {
    75         var matchMedia = function() {
    76                 // Include the 'heartz' as a way to have a non matching MQ to help terminate the join. See <https://git.io/vznFH>.
    77                 var prefixes = [ '-webkit-', '-moz-', '-o-', '-ms-' ];
    78                 var query = [ '(', prefixes.join( 'touch-enabled),(' ), 'heartz', ')' ].join( '' );
    79                 return window.matchMedia && window.matchMedia( query ).matches;
    80         };
     74twentytwenty.touchEnabled = {
    8175
    82         if ( ( 'ontouchstart' in window ) || ( window.DocumentTouch && document instanceof window.DocumentTouch ) || matchMedia() ) {
    83                 document.body.classList.add( 'touch-enabled' );
     76        init: function() {
     77                var matchMedia = function() {
     78                        // Include the 'heartz' as a way to have a non matching MQ to help terminate the join. See <https://git.io/vznFH>.
     79                        var prefixes = [ '-webkit-', '-moz-', '-o-', '-ms-' ];
     80                        var query = [ '(', prefixes.join( 'touch-enabled),(' ), 'heartz', ')' ].join( '' );
     81                        return window.matchMedia && window.matchMedia( query ).matches;
     82                };
     83
     84                if ( ( 'ontouchstart' in window ) || ( window.DocumentTouch && document instanceof window.DocumentTouch ) || matchMedia() ) {
     85                        document.body.classList.add( 'touch-enabled' );
     86                }
    8487        }
    85 }() );
     88}; // twentytwenty.touchEnabled
    8689
    8790/*      -----------------------------------------------------------------------------------------------
    8891        Cover Modals
     
    745748        twentytwenty.smoothScroll.init();       // Smooth scroll to anchor link or a specific element
    746749        twentytwenty.modalMenu.init();  // Modal Menu
    747750        twentytwenty.primaryMenu.init();        // Primary Menu
     751        twentytwenty.touchEnabled.init();       // Add class to body if device is touch-enabled
    748752} );
    749753
    750754/*      -----------------------------------------------------------------------------------------------