【问题标题】:jQuery loading order in WordpressWordpress 中的 jQuery 加载顺序
【发布时间】:2016-02-02 19:39:33
【问题描述】:

我有一个 jQuery 脚本,它读取 img 高度并将样式标签添加到 head 标签。

jQuery

var img = document.getElementById('logomini');  
height = img.clientHeight;

$(function (){
    $("<style type='text/css' id='style1'>#menu ul { line-height: "+ height +"px }</style>").appendTo("head");
});

问题:有时脚本工作正常,有时却不行。当我刷新我的网站(Wordpress)时,行高是 80px 或 0px。我认为这是脚本加载的问题。当脚本加载速度快于 img 时,它显示 0px。但这只是我的猜测......脚本标签就在&lt;/body&gt;标签之前。

my demo page

有什么想法吗?

【问题讨论】:

  • 您在加载图像之前设置高度变量,您从中获取高度。您应该在文档就绪函数中定义变量。
  • 好吧,还是不行

标签: jquery html wordpress load-order


【解决方案1】:

如果您想确保图像首先完全加载,请使用以下代码:

/* In WordPress, $ may be used for other libraries, so use this safer "document ready" method */
jQuery(function($) {
    /* wait until everything in the window has loaded */
    $(window).load(function() {
        var img = document.getElementById('logomini');  
        height = img.clientHeight;
        // The above two lines could be simplified like so:  
        var height = $('#logomini').height();
        $("<style type='text/css' id='style1'>#menu ul { line-height: "+ height +"px }</style>").appendTo("head");
    });
});

另请参阅此答案:Delaying a jquery script until everything else has loaded

【讨论】:

  • 抱歉 :) 没有任何改变。不过,有时工作正常,有时却不行。
猜你喜欢
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多