【问题标题】:Rails: Running Javascript only after CSS loadedRails:仅在加载 CSS 后运行 Javascript
【发布时间】:2014-03-01 23:37:01
【问题描述】:

我在 turbolinks 加载的 .js 文件中使用 Google Maps API V3。

$('#google-map')元素加载时触发地图渲染:

function initGoogleMap() {
   ...
   var map = new google.maps.Map($('#google-map').get(0), mapOptions);
   ...
}

$('#google-map').ready(function() {
  initGoogleMap();
});

问题是initGoogleMap()运行时,它使用$('#google-map')的宽高来渲染地图,此时宽高为0

宽度和高度在以控制器命名的 .scss 文件中定义:

.map {
    height: 300px;
    width: 400px;

    #google-map {
        height: 300px;
        width: 400px;
    }
}

我使用的是 rails 的约定,所以在我的视图模板中没有提及 .js 文件名或 .scss 文件名。

如何确保脚本仅在样式表加载后运行?

【问题讨论】:

    标签: javascript jquery css ruby-on-rails turbolinks


    【解决方案1】:

    第 1 部分:页面特定 JS:

    在此处查看 Rails 管道中页面特定 JS 的一种可能解决方案:https://stackoverflow.com/a/11975103/1162491

    第 2 部分:应用 CSS 规则后运行 JS:

    我假设您的 CSS 已加载到应用程序布局的 <head> 中。在模板的底部,include the page-specific javascriptjavascript_include_tag 并在文档准备好时加载您的 javascript。这应该可以解决您的问题;但是,就像this SO post shows 一样,将样式表标签放在您的 javascript 标签之前可能并不总是会产生预期的行为,因为 CSS 是异步加载的。因此,正如该帖子中的一个答案所暗示的那样,

    $(window).load(function() { $('#abc')...} ); 
    

    可能始终比$(document).ready() 表现更好。

    【讨论】:

    • 您能否解释一下我的问题与您的答案第 1 部分之间的联系?另外,那里的哪些答案似乎与我的问题相关,为什么?
    • 大概您不希望/不需要所有的 javascript 在文档的最后运行,因此,将您需要的内容放在最后一个不同的 javascript 文件中。我已经修复了直接转到此答案的链接:stackoverflow.com/a/11975103/1162491
    • $(window).load 似乎解决了我所有的问题。
    【解决方案2】:

    正如 jquery 的 ready() 函数所解释的(http://api.jquery.com/ready/),

    In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
    

    所以使用 load() 方法可能会解决您的问题。

    $('#google-map').load(function() {
      initGoogleMap();
    });
    

    【讨论】:

    • 我尝试过使用load,但现在代码根本无法运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2018-02-06
    • 1970-01-01
    • 2011-10-08
    • 2012-06-13
    • 1970-01-01
    • 2015-07-09
    相关资源
    最近更新 更多