Conditionally load JS script for Desktop PC (NOT t

2019-08-28 11:18发布

问题:

On my website I use a JS for parallax scrolling. I want to conditionally load that JS only on Desktop PCs with >= 1025 px width. And I desperately need help with optimizing and putting it together.

What I currently have

The sections that have the Parallax-Effect have several data-attributes:

<section id="profile" class="slide" data-speed="2" data-offsetY="185" data-type="background">

The sections also have a background image set up via css.

.slide { 
padding:0;
width:100%; 
position:relative; 
margin:0 auto; 
overflow:hidden;
}
#profile { 
background: url(../assets/backgrounds/02_profile_back.jpg) 50% 185px no-repeat fixed, #0f0f11;
height:1027px;
}

JAVASCRIPT

What I got so far:

  • Custom Function (myFunction) that's executed on $(document).ready
  • Check on window.on('scroll resize load')
  • Execute JS @breakpoint of 1025 px via enquire.js (match)
  • Set alternative / default behaviour (unmatch)
  • Use the listener of enquire.js.

Here's the code so far: (The Parallax Script is: by Richard Shepherd, modified by Ryan Boudreaux)

function myFunction(){

// Cache the Window object
$window = $(window);

// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {  
    $(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
    $(this).data('Xposition', $(this).attr('data-Xposition'));
    $(this).data('speed', $(this).attr('data-speed'));
});

// For each element that has a data-type attribute
$('section[data-type="background"]').each(function(){

    // Store some variables based on where we are
    var $self = $(this),
        offsetCoords = $self.offset(),
        topOffset = offsetCoords.top;



// This is the part I'm having trouble with //
// When the window is scrolled, resized, loaded...
    $(window).on('scroll resize load',function(e){

        // Check if Screen-width is higher or equal to 1025px
        enquire.register('screen and (min-width:1025px)', {

            match : function() {

            // If this section is in view
            if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
            ( (topOffset + $self.height()) > $window.scrollTop() ) ) {
            // Scroll the background at var speed
            // the yPos is a negative value because we're scrolling it UP!                              
            var yPos = -($window.scrollTop() / $self.data('speed')); 
            // If this element has a Y offset then add it on
            if ($self.data('offsetY')) {
                yPos += $self.data('offsetY');
            }
            // Put together our final background position
            var coords = '50% '+ yPos + 'px';
            // Move the background
            $self.css({ backgroundPosition: coords });
                }; // in view
        },

        unmatch : function() {
            $('#profile').css('background-position', '50% 0px');
        }

    }).listen(); // Check Screen Width

    }); // window load resize scroll

}); // each data-type
} // myFunction

What I want to implement but cannot figure out

I'm looking for a way to squeeze in another if-loop, that only executes the first "match"-part if the device is NOT a Touch Device. I found var isTouch = (('ontouchstart' in window) || !!('msmaxtouchpoints' in window.navigator)); but I cannot figure out how to implement this so everything fits together.

Questions

  1. Is there a way of realizing the condition "if desktop PC with 1025px and higher width"?
  2. Is there a best practice / common solution for conditionally loading that parallax-JS at the end of mobile-first?

I know my code is a mess, you can probably tell by now that I'm a noob. Nevertheless, I'm eager to learn and am looking forward to your replies. Thanks a bunch!

回答1:

Well you could use yepnope to load your JavaScript dynamically, and then use window.innerWidth to check the screen width. I'm not sure on checking specifically for a mobile device, unless you use browser user agent strings.