jQuery Wordpress 中的加载顺序

jQuery loading order in Wordpress

我有一个 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。但这只是我的猜测......脚本标签就在 </body> 标签之前。

my demo page

有什么想法吗?

如果您想先确定图像是否已完全加载,请使用此代码:

/* 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