jQuery工作和不工作;它第一次加载时不起作用

jQuery works and doesn't work when it first loads

本文关键字:工作 加载 不起作用 第一次 jQuery      更新时间:2023-09-26

我有一个rails应用程序,我正试图在.中实现一些jQuery

我有两个脚本,一个在第一次加载时工作,另一个需要重新加载。我在application.js中修改了涡轮链接,现在这个脚本出现了问题。现在,同样的问题也发生在另一个脚本上。

有效的:

jQuery(document).ready(function($){
//set animation timing
var animationDelay = 5000,
    //loading bar effect
    barAnimationDelay = 3800,
    barWaiting = barAnimationDelay - 3000, //3000 is the duration of the transition on the loading bar - set in the scss/css file
    //letters effect
    lettersDelay = 50,
    //type effect
    typeLettersDelay = 150,
    selectionDuration = 500,
    typeAnimationDelay = selectionDuration + 800,
    //clip effect 
    revealDuration = 600,
    revealAnimationDelay = 1500;
initHeadline();

不起作用的:

jQuery(document).ready(function($){
//if you change this breakpoint in the style.css file (or _layout.scss if you use SASS), don't forget to update this value as well
var MQL = 1170;
//primary navigation slide-in effect
if($(window).width() > MQL) {
    var headerHeight = $('.box-header').height();
    $(window).on('scroll',
    {
        previousTop: 0
    }, 
    ...
    ...

等等。

为什么会发生这种情况?CSS或调用它的页面有问题吗?

Turbolinks可能会在Rails应用程序中造成问题,因为它试图通过维护页面的<head>元素中列出的资产来节省开销(除其他外(。当您使用完全加载(通过刷新按钮(加载页面时,会发生一个实际的就绪事件,脚本也会正常工作。另一方面,如果您以其他方式(通过链接(访问页面,Turbolinks会尝试重用<head>元素,因此不会触发就绪事件。

过去的解决方案是简单地完全禁用Turbolinks,方法是删除application.js中的require行,或者通过链接(数据:{no_turbolink:true}(。使用Rails 4.2.x和5.x,您可以监听与Turbolinks相关的事件,该事件应该在正常就绪事件之前工作的地方工作。

来自文件:

但是由于Turbolinks覆盖了正常的页面加载过程,它所依赖的事件将不会被激发。如果你有代码看起来像这个

$(document).ready ->
  alert "page has loaded!"

您必须更改代码才能执行此操作:

$(document).on "turbolinks:load", ->
  alert "page has loaded!"

(为了清晰起见,报价略有重排(