[英]jQuery works and doesn't work when it first loads
我有一個Rails應用,正在嘗試實現一些jQuery。
我有兩個腳本,一個腳本在第一次加載時有效,另一個腳本需要重新加載。 我遇到了一個問題,該問題現在可以在application.js中修改Turbolinks的情況下工作。 現在,另一個腳本也發生了相同的問題。
有效的一種:
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或被調用的頁面是否存在問題?
渦輪鏈接可能會在Rails應用程序中引起問題,因為它試圖通過維護頁面<head>
元素中列出的資產(以及其他方法)來節省開銷。 當您使用滿載(通過刷新按鈕)加載頁面時,將發生實際的就緒事件,並且腳本可以工作。 另一方面,如果您要通過其他方式(通過鏈接)訪問頁面,Turbolinks會嘗試重用<head>
元素,因此不會觸發ready事件。
過去的解決方案是完全通過在application.js中刪除它的要求行或通過鏈接來完全禁用Turbolinks(數據:{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!"
(為了清楚起見,報價略有重新排列)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.