等待JQuery执行,直到加载了整个页面,中断执行

Wait for JQuery execution until whole page is loaded breaks execution

本文关键字:执行 中断 加载 JQuery 等待      更新时间:2024-05-20

我有一个JQuery脚本,用于在用户使用JQuery.wollow/.sollTop函数向下滚动一定数量的像素后加载时事通讯订阅弹出窗口。

目前它都封装在中

jQuery(document).ready(function($)

问题是常见的缓存和图像问题,订阅框会到处弹出。我读过关于使用.load函数延迟jQuery直到页面完全加载的文章。但是,当我更换时

jQuery(document).ready

带有

jQuery(window).load(function($){
  //your code here
});

功能完全中断。

我想注意的是,我正在使用WordPress,并有这样的脚本排队:


function enfold_child_custom_scripts(){
    // Register and Enqueue a Script
    // get_stylesheet_directory_uri will look up child theme location
    wp_register_script( 'custom-js', get_stylesheet_directory_uri() . '/custom.js', array('jquery'));
    wp_enqueue_script( 'custom-js' );
}
add_action('wp_enqueue_scripts', 'enfold_child_custom_scripts');

这是我现在的JS/jQuery代码。

jQuery(document).ready(function($) {
    jQuery("#nl-pop").hide(); //hide nl block initially
    var disableFade = "false";
    var startShowTop = jQuery("#newsletter-cta").offset().top - 3500;
    var startHide = jQuery("#newsletter-cta").offset().top - jQuery(window).height(); //Hide when the viewport is reached
    jQuery('#no-thanks').click(function(event) {
         event.preventDefault();
         jQuery('#nl-pop').fadeOut('slow');
         disableFade = "true";
    }); 
 jQuery(window).scroll(function() {
        if(jQuery(window).scrollTop() < (startShowTop) ) //when scrollposition is smaller than the first point
        {
             jQuery("#nl-pop").fadeOut(200); // Hide when in the upper part of the page
        }
        else //when reached the lower part of the page
        {
            if(jQuery(window).scrollTop() > startShowTop && $(window).scrollTop() < startHide && disableFade==="false") { //When reached the show position but not as far down as the hide position
                jQuery("#nl-pop").fadeIn(200); //show
            }
            else if(jQuery(window).scrollTop() > (startHide) ) { //scrolled down to the bottom newsletter box
                jQuery("#nl-pop").fadeOut(200); //hide
            }
        } 
    });   
});

startShowTopstartHide的计算移动到.scroll()内部。这样,它们的价值就不会受到卸载元素的影响。相反,它们将取决于页面的当前状态(很可能是在加载了整个页面之后)。