等待JQuery执行,直到加载了整个页面,中断执行
Wait for JQuery execution until whole page is loaded breaks execution
我有一个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
}
}
});
});
将startShowTop
和startHide
的计算移动到.scroll()
内部。这样,它们的价值就不会受到卸载元素的影响。相反,它们将取决于页面的当前状态(很可能是在加载了整个页面之后)。
相关文章:
- 无法在通过jQuery的ajax加载的页面中执行javascript
- JavaScript执行暂时挂起页面
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 当js函数's已执行
- 哪个先执行
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- HTML表单提交时未执行外部函数
- 等待JQuery执行,直到加载了整个页面,中断执行
- HTML 看不到 Javascript 代码;PHP 代码中的执行中断而没有错误
- JavaScript 函数的执行可以被中断吗?
- 在执行 ajax 调用返回错误时中断 jquery for 循环
- JS Popup 会中断 javascript 的执行
- ie8javascript停止脚本我可以使用settimeout来中断执行并避免错误
- Javascript异步执行:将一个回调中断运行的代码
- 函数/回调执行可以被外部调用中断吗?
- 如何(优雅地)用Q中断Promises链的执行
- 从定时循环中中断javascript的执行
- 如何多次执行相同的单击事件而不中断前一个事件的执行
- 使用getTime的停止/中断函数执行
- 如何在 AJAX 的成功中中断执行和显示错误