JavaScript file doesn't load after page transition with barba.js

元气小坏坏 提交于 2019-12-08 05:02:49

问题


I have a website with a link. When I click the link I want a smooth page transition to the next page using jQuery. I got the the HTML elements inside the barba DOM to fade out. But when the next page tries to load, all BUT the JavaScript loads.

This is my code: (index.html)

   <div id="barba-wrapper" class="wrapper">
    <div class="barba-container">
        <div class="container">
            <span class="text1">Hey There!</span>
            <span class="text2">This is my portfolio!</span>
            <a id="homeLink" href="./home.html">Click me to continue</a>
        </div>
    </div>
</div>
<script>
    $('document').ready(function(){
        var transEffect = Barba.BaseTransition.extend({
            start: function(){
              this.newContainerLoading.then(val => this.fadeInNewcontent($(this.newContainer)));
            },
            fadeInNewcontent: function(nc) {
              nc.hide();
              console.log('stuff should be hidden');
              var $el = $(this.newContainer);
              var _this = this;
              $(this.oldContainer).fadeOut(1000).promise().done(() => {
                nc.css('visibility', 'visible');
                nc.fadeIn(1000, function(){
                console.log('new content should fade in.');
                _this.done();
                })
              });
            }
        });
        Barba.Pjax.getTransition = function() {
          return transEffect;
        }
        Barba.Pjax.start();
    });
</script>

I can see the the console logs in the console but JavaScript doesn't load.

This is the page I'm trying to load: (home.html)

<div id="barba-wrapper" class="wrapper">
    <div class="barba-container">
        <canvas></canvas>
        <script src="canvas.js"></script>
    </div>
</div>

I get no errors whatsoever. Also I have seen a question on here with the same problem as mine, but it was very unclear. (and does not have any answers so far) Thanks!


回答1:


In Barba, scripts don't evaluated when loading a new container. It can be done easily using Events.

Barba.Dispatcher.on('newPageReady', function (currentStatus, oldStatus, container) {
    $(container).find('script').each(function (i, script) {
        var $script = $(script);
        $.ajax({
            url: $script.attr('src'),
            cache: true,
            dataType: 'script',
            success: function () {
                $script.trigger('load');
            }
        });
    });
});



回答2:


Add this line:

document.getElementsByTagName("head")[0].innerHTML += "<meta http-equiv=\"refresh\" content=\"1\">"; 

inside below function

fadeInNewcontent: function(nc) {

}


来源:https://stackoverflow.com/questions/53744257/javascript-file-doesnt-load-after-page-transition-with-barba-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!