Search code examples
javascriptjquerypjaxytplayer

jquery.mb.YTPlayer.js not working after initial page load with InstantClick.js


Is there any way to make jquery.mb.YTPlayer.js work after initial page load with InstantClick.js?

The plugin works fine on initial page load, but after that it doesn't work anymore.

Here is how I originally initialized it, works fine on page load but not after further navigation:

app.js

InstantClick.on('change', function() {
        $(".player").mb_YTPlayer();
});

I then spent hours on trying to debug and ended up with something like this:

app.js

InstantClick.on('change', function() {
    if ($(".mbYTP_wrapper")[0]){
        $(".player").playerDestroy();
        console.log('destroyed');
    }
    if (window.YT) {
        console.log(window.YT);
    }

    $(".player").mb_YTPlayer();
});

in jquery.mb.YTPlayer.js I tried adding this to .playerDestroy:

playerDestroy: function () {
        jQuery("#YTAPI").remove();
}

On the initial page load the object window.YT doesn't exist of course, but then after the first page navigation I get 1 Object, then I get 2 Objects for 1 navigation, then I get 3 objects and so on.. The picture below is after 4 page navigations, 10 window.YT objects.

enter image description here


Solution

  • I had checked both plugins you use, and concluded that the problem is with your codes getting reloaded on every navigation.

    To tackle that problem, try using data-no-instant attribute for scripts which you need to load only once. That may include following:

    Youtube widget: <script type="text/javascript" id="www-widgetapi-script" src="https://s.ytimg.com/yts/jsbin/www-widgetapi-vflr-TgN1/www-widgetapi.js" async="" data-no-instant></script>

    Youtube API: <script src="https://www.youtube.com/player_api?v=2.7.6" id="YTAPI" data-no-instant></script>

    JQuery library: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js" data-no-instant></script>

    YT Player plugin: <script type="text/javascript" src="inc/jquery.mb.YTPlayer.js" data-no-instant></script>

    InstantClick plugin: <script src="instantclick.min.js" data-no-instant></script>

    Put Following Codes Too inside: <script data-no-instant></script>

    Also destroy your YT Player instance on mouseup and touchend events.

    $(body).on('mouseup touchend',".player",function(){
        $(".player").playerDestroy();
    });
    

    And re-init the YT Player on InstantClick event change.

    InstantClick.on('change',function(){
        $(".player").mb_YTPlayer();
    });
    

    Should you do that, I think the problem should be resolved.