导致内存泄漏的Javascript

时间:2018-01-24 18:33:15

标签: javascript jquery html5

我不能为我的生活弄清楚为什么要加载这个页面... http://polyphonic.hannahkingdev.com/work/cowboys-angels或任何其他视频页面有时会导致浏览器挂起,然后提示我停止导致浏览器放慢速度的脚本。

如果要继续播放视频,那么当您关闭该页面时,浏览器就会没有响应。在FFox,Safari和amp;中也是如此。铬。

任何寻找内存泄漏的帮助都将非常受欢迎。我完全被这个困扰了。

非常感谢

var $ = jQuery.noConflict();
$(document).ready(initPage);

// -- Init -- //
function initPage() {
    resizeWork();
    //hoverWorkImg();
};
// -- Pageload -- //
$(document).ready(function() {
    $(".animsition").animsition({
        inClass: 'overlay-slide-in-left',
        outClass: 'overlay-slide-out-left',
        inDuration: 1500,
        outDuration: 800,
        linkElement: 'a:not([target="_blank"]):not([href^=#]):not([href^=mailto]:not([href^=tel])',
        loading: true,
        loadingParentElement: 'body', //animsition wrapper element
        loadingClass: 'animsition-loading',
        loadingInner: '', // e.g '<img src="loading.svg" />'
        timeout: false,
        timeoutCountdown: 5000,
        onLoadEvent: true,
        browser: [ 'animation-duration', '-webkit-animation-duration'],
        overlay : true,
        overlayClass : 'animsition-overlay-slide',
        overlayParentElement : 'body',
        transition: function(url){ window.location.href = url; }
    });
});
// -- Navigation -- //
if (document.getElementById('menu-button') !=null) {
    var button = document.getElementById('menu-button');
    var menu = document.getElementById('menu-main-navigation');
    var menuPos = window.innerHeight;
    var menuFixed = false;

    button.addEventListener('click', function(ev){
        ev.preventDefault();
        menu.classList.toggle('navigation--isOpen');
        button.classList.toggle('navigation-button--isOpen');
    })

    updateMenuPosition();
    window.addEventListener('resize', updateMenuPosition);

    // -- Highlight nav -- /
    var $navigationLinks = $('#menu-main-navigation > li > a');
    var $sections = $($("section").get().reverse());
    var sectionIdTonavigationLink = {};
    $sections.each(function() {
        var id = $(this).attr('id');
        sectionIdTonavigationLink[id] = $('#menu-main-navigation > li > a[href="#' + id + '"]');
    });
    function throttle(fn, interval) {
        var lastCall, timeoutId;
        return function () {
            var now = new Date().getTime();
            if (lastCall && now < (lastCall + interval) ) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(function () {
                    lastCall = now;
                    fn.call();
                }, interval - (now - lastCall) );
            } else {
                lastCall = now;
                fn.call();
            }
        };
    }
    function highlightNavigation() {
        var scrollPosition = $(window).scrollTop();
        $sections.each(function() {
            var currentSection = $(this);
            var sectionTop = currentSection.offset().top;
            if (scrollPosition >= sectionTop) {
                var id = currentSection.attr('id');
                var $navigationLink = sectionIdTonavigationLink[id];
                if (!$navigationLink.hasClass('active')) {
                    $navigationLinks.removeClass('active');
                    $navigationLink.addClass('active');
                }
                return false;
            }
        });
    }

    $(window).scroll( throttle(highlightNavigation,100) );
}

function updateMenuPosition(){
    if(menuFixed){
        menu.classList.remove('navigation--white');
        menuPos = menu.offsetTop;
        menu.classList.add('navigation--white');
    } else {
        menuPos = menu.offsetTop;
    }
    updateMenuAttachment();
}

updateMenuAttachment();
window.addEventListener('scroll', updateMenuAttachment);

function updateMenuAttachment(){
    var scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
    if(!menuFixed && scrollPos >= window.innerHeight - 200){
        menu.classList.add('navigation--white');
        menuFixed = true;
    } else if(menuFixed && scrollPos < window.innerHeight - 200){
        menu.classList.remove('navigation--white');
        menuFixed = false;
    }
}


// -- Smooth scroll to anchor -- /
$('a[href*="#"]')
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (this.hash=="#work") {;
            var offsetT = (target.offset().top)-90;
        } else {
            var offsetT = (target.offset().top);
        }
        if (target.length) {
            event.preventDefault();
            $('html, body').animate({
              scrollTop: offsetT
            }, 1000, function() {

            });
        }
    }
});

// -- Back to top -- /
jQuery(document).ready(function($){
    var offset = 300,
        offset_opacity = 1200,
        scroll_top_duration = 700,
        $back_to_top = $('.cd-top');

    $(window).scroll(function(){
        ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
        if( $(this).scrollTop() > offset_opacity ) { 
            $back_to_top.addClass('cd-fade-out');
        }
    });
    $back_to_top.on('click', function(event){
        event.preventDefault();
        $('body,html').animate({
            scrollTop: 0 ,
             }, scroll_top_duration
        );
    });

});

// -- Animate -- /
new WOW().init();

// -- Inline all SVGs -- /
jQuery('img.svg').each(function(){
    var $img = jQuery(this);
    var imgID = $img.attr('id');
    var imgClass = $img.attr('class');
    var imgURL = $img.attr('src');

    jQuery.get(imgURL, function(data) {
        // Get the SVG tag, ignore the rest
        var $svg = jQuery(data).find('svg');

        // Add replaced image's ID to the new SVG
        if(typeof imgID !== 'undefined') {
            $svg = $svg.attr('id', imgID);
        }
        // Add replaced image's classes to the new SVG
        if(typeof imgClass !== 'undefined') {
            $svg = $svg.attr('class', imgClass+' replaced-svg');
        }

        // Remove any invalid XML tags as per http://validator.w3.org
        $svg = $svg.removeAttr('xmlns:a');

        // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
        if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
            $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
        }

        // Replace image with new SVG
        $img.replaceWith($svg);

    }, 'xml');

});


// -- work grid -- /
function resizeWork() {
    var div = $('.work article');
    div.css('height', div.width() / 1.9);
}
function hoverWorkImg() {
    $('article a').on('mouseenter', function () {
        $(this).find('.imagehover:hidden').fadeIn(700);
        $(this).find('.second:hidden').fadeIn(700);
        $(this).find('.first:visible').fadeOut(700);
    })

    $('article a').on('mouseleave', function () {
        $(this).find('.imagehover:visible').fadeOut(700);
        $(this).find('.second:visible').fadeOut(700);
        $(this).find('.first:hidden').fadeIn(700);
    })
}

// -- Video Page -- /
    function playVideoInPage() {
        showModal(false);
        initPlayer();
        startPlay();
    }
    var $video,
        $playPauseButton,
        $muteButton,
        $seekBar,
        isMouseMove=false,
        $timing;

    function showModal(html) {
        if (html !== false) {
            $('.work-video').html(html).fadeIn();
        }
        else {
            $('.work-video').fadeIn();
        }
        hidePlayerControls();
    }

    function initPlayer() {
        $('#video').css('height', $(window).height());
        $video = $('.video-container'),
            $playPauseButton = $('#play-pause'),
            $muteButton = $('#mute'),
            $seekBar = $('#seek-bar'),
            $timing = $('.timing');
        /*setTimeout('showPlayerControls()', 1500);*/

        $playPauseButton.on('click', function () {
            if ($video.get()[0].paused == true) {
                $video.get()[0].play();
                $playPauseButton.removeClass('paused');
            }
            else {
                $video.get()[0].pause();
                $playPauseButton.addClass('paused');
                $timing.stop(true, true);
            }
        })

        $muteButton.on('click', function () {

            if ($video.get()[0].muted == false) {
                $video.get()[0].muted = true;

                $muteButton.addClass('muted');
            }
            else {
                $video.get()[0].muted = false;
                $muteButton.removeClass('muted');
            }
        })

        $seekBar.on("click", function (e) {
            var x = e.pageX - $(this).offset().left,
                widthForOnePercent = $seekBar.width() / 100,
                progress = x / widthForOnePercent,
                goToTime = progress * ($video.get()[0].duration / 100);

            goToPercent(progress)
            $video.get()[0].currentTime = goToTime;
        });

        $video.get()[0].addEventListener("timeupdate", function () {
            var value = (100 / $video.get()[0].duration) * $video.get()[0].currentTime;
            goToPercent(value)
        });

    }

    function startPlay() {
        $playPauseButton.click();
    }

    function goToPercent(value) {
        $timing.css('width', value + '%');
    }

    function showPlayerControls() {
        $('.controls').fadeIn();
        isMouseMove=true;
    }

    function hidePlayerControls() {
        $('.controls').fadeOut();
    }

    function hidePlayerControls() {
        setInterval(function() {
            if (!isMouseMove) {
                hidePlayerControls();
            }
            isMouseMove=false;
        }, 4000);

        $(document).mousemove(function (event) {
            isMouseMove=true;
            showPlayerControls();
        });
    }

1 个答案:

答案 0 :(得分:0)

最可能的原因是这里的代码:

function hidePlayerControls() {
    setInterval(function() {
        if (!isMouseMove) {
            hidePlayerControls();
        }
        isMouseMove=false;
    }, 4000);

所以 4秒开始一个新的间隔(间隔=重复直到取消)。

在第一种情况下,您可能希望将其更改为setTimeout

function hidePlayerControls() {
    setTimeout(function() {
        if (!isMouseMove) {
            hidePlayerControls();
        }
        isMouseMove=false;
    }, 4000);

在第二种情况下,您可以将鼠标移动时将其更改为取消上一次超时 - 这称为 debouncing - 虽然通常间隔时间较短,但原则是同样的。

作为一般调试提示,自由添加console.log语句并观察您的浏览器控制台(还有其他方法,这是基本调试的第一步),例如:

function hidePlayerControls() {
    console.log("hidePlayerControls() called");
    setInterval(function() {
        console.log("hidePlayerControls - interval triggered", isMouseMove);
        if (!isMouseMove) {
            hidePlayerControls();
        }
        isMouseMove=false;
    }, 4000);

了解这个被称为

的次数