最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Immediate (e.g. without DOMContentLoaded) JS not working

programmeradmin2浏览0评论

I'm implementing smooth page transitions using JS / CSS on a site following this tutorial.

In the tutorial it says I should load the JS immediately after the browser has started to receive and render the first bytes of the page, not wating for DOMContentLoaded etc. This doesn't work for me, and I have to add DOMContentLoaded to make the script work. Here's the section that's not working:

function fadeInPage() {
  if (!window.AnimationEvent) { return; }
  var fader = document.getElementById('fader');
  fader.classList.add('fade-out');

})

Here's how it looks when it works:

window.addEventListener('DOMContentLoaded', function() {
  if (!window.AnimationEvent) { return; }
  var fader = document.getElementById('fader');
  fader.classList.add('fade-out');

})

Here's the full script:

function fadeInPage() {

window.addEventListener('DOMContentLoaded', function() {
  if (!window.AnimationEvent) { return; }
  var fader = document.getElementById('fader');
  fader.classList.add('fade-out');

})

document.addEventListener('DOMContentLoaded', function() {
    if (!window.AnimationEvent) { return; }
    var anchors = document.getElementsByTagName('a');
    for (var idx=0; idx<anchors.length; idx+=1) {
        if (anchors[idx].hostname !== window.location.hostname) {
            continue;
        }
        anchors[idx].addEventListener('click', function(event) {
            if (event.metaKey || event.ctrlKey) return;
            var fader = document.getElementById('fader'),
            anchor = event.currentTarget;

            var listener = function() {
                window.location = anchor.href;
                fader.removeEventListener('animationend', listener);
            };
            fader.addEventListener('animationend', listener);

            event.preventDefault();
            fader.classList.add('fade-in');
        });
    }
});

window.addEventListener('pageshow', function (event) {
    if (!event.persisted) {
        return;
    }
    var fader = document.getElementById('fader');
    fader.classList.remove('fade-in');
});

Here's the original author's example page that DOES work with no DOMContentLoaded. I'm not sure why this works, but mine doesn't.

Finally, I'm using the following function to add the inline script. I don't know if this is relevant, but I've included it for completeness:

function fader_script() {
wp_enqueue_script('fader', get_template_directory_uri() .'/js/fader.js', array(), '1.0', true);
    wp_add_inline_script('fader', $script, 'before');
}
add_action('wp_enqueue_scripts', 'fader_script');
发布评论

评论列表(0)

  1. 暂无评论