简体   繁体   中英

jQuery loading order in Wordpress

I have a jQuery script that reads img height and adds style tag to head tag.

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. I think it's a problem with script loading. When script is loading faster than img it showing 0px. But it's only my guess... The script tag is right before </body> tag.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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