Rails项目:jQuery插件在刷新前未加载

Rails Project: jQuery Plugin not loading until refresh

本文关键字:刷新 加载 插件 项目 jQuery Rails      更新时间:2023-09-26

我在Rails 4中构建了一个应用程序。我在我的展示页面上有以下JS插件,但它们似乎只有在我手动重新加载页面时才能工作。

我读到这可能是由于涡轮链接,但由于这些插件在身体而不是头部,这似乎不是涡轮链接的问题。

我甚至试着把这些粘贴在页眉和页脚标签中,但这些标签给了我同样的问题。有时,其中一个插件加载,另一个不加载。

下面的第一个插件是AddThis社交按钮,另一个是图片库。

有什么建议吗?

演示页面http://mktdemo.herokuapp.com/listings/45

<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ashfaaq">
</script>
    <script>
        jQuery(document).ready(function($) {
      $('#gallery-1').royalSlider({
        fullscreen: {
          enabled: true,
          nativeFS: true
        },
        controlNavigation: 'none',
        autoScaleSlider: true, 
        autoScaleSliderWidth: 960,     
        autoScaleSliderHeight: 850,
        imageScaleMode: 'fit-if-smaller',
        navigateByClick: true,
        numImagesToPreload:2,
        arrowsNav:true,
        arrowsNavAutoHide: true,
        /* arrowsNavHideOnTouch: true, */
        keyboardNavEnabled: true,
        fadeinLoadedSlide: true,
        globalCaption: false,
        globalCaptionInside: false,
        loop: true,
        thumbs: {
          appendSpan: true,
          firstMargin: true,
          paddingBottom: 4
        } 
      });
    });
    </script>

您可以在此处找到问题的答案:Rails 4 turbo链接阻止jQuery脚本运行

Rails4使用Turbolinks,它只加载页面javascript和css一次,然后只替换标题中的正文和标题。这就是为什么jQuery(document).ready只有在重新加载页面时才能工作的原因。

为了触发您的javascript,您必须使用Turbolinks事件,如

page:change the page has been parsed and changed to the new version and on DOMContentLoaded

page:load is fired at the end of the loading process.

更多详细信息请点击此处:https://github.com/rails/turbolinks/#events

在这里,您可以更换

jQuery(document).ready(function($) {
...

通过

$(document).on('page:load', function($) { 
...

听起来涡轮链接是造成问题的原因。

你可以安装这个宝石:Jquery Turbolinks

或者你可以更换

jQuery(document).ready(function(
     ....
));

带有

$(document).on('page:load', function(
    ....
));

以下是一个很好的复制/粘贴,说明了为什么涡轮链接会导致jquery出现一些问题。

TurboLinks是一个类似PJAX的库,它异步请求下一页的内容并将其插入当前页面的正文中,而不需要重新加载整个页面。它很好地加快了页面加载时间。但是,由于页面是重新加载的,因此会触发DOMContentLoaded事件,并且不会触发jQuery document.ready事件。

我在Rails 5上的jQuery图像库也遇到了同样的问题。除非刷新页面,否则它不会加载。经过一年(断断续续)的尝试,以下是对我有效的破解方法:

将jQuery库代码封装在一个函数中:

var delayLoad = function(){
 $('#gallery-1').royalSlider({
 ...
 })
}

然后用setTimeout:调用它

setTimeout(delayLoad, 250)

这每次都为我解决了问题,而无需刷新页面。