简体   繁体   English

jQuery在Wordpress中的加载顺序

[英]jQuery loading order in Wordpress

I have a jQuery script that reads img height and adds style tag to head tag. 我有一个jQuery脚本,可读取img高度并将样式标签添加到head标签。

jQuery 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");
});

The problem: sometimes the script is working properly and sometimes it's not. 问题是:有时脚本可以正常工作,有时却不能。 When I'm refreshing my website (Wordpress) the line-height is 80px or 0px. 刷新网站(Wordpress)时,行高为80px或0px。 I think it's a problem with script loading. 我认为这是脚本加载的问题。 When script is loading faster than img it showing 0px. 当脚本的加载速度比img快时,显示为0px。 But it's only my guess... The script tag is right before </body> tag. 但这只是我的猜测... script标签就在</body>标签之前。

my demo page 我的演示页面

Any ideas? 有任何想法吗?

If you want to be sure the image is fully loaded first, then use this code: 如果要确保首先将图像完全加载,请使用以下代码:

/* 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");
    });
});

Also see this answer: Delaying a jquery script until everything else has loaded 另请参阅以下答案: 将jquery脚本延迟到其他所有内容都已加载之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM