简体   繁体   中英

How can I make it so that I don't see hidden elements while the page is loading (jQuery)?

I'm using the following jQuery code to hide and show some HTML element in the page:

/* Previous
------------------------------------------------------------ */
jQuery(document).ready(function($) {
    $('li.menu-item a').hover(
    function() {
        var $this = $(this);
        $this.css('backgroundImage', $this.css('backgroundImage').replace("_off","_over"));
    },
    function() {
        var $this = $(this);
        $this.css('backgroundImage', $this.css('backgroundImage').replace("_over","_off"));
    });

/* Workarounds
------------------------------------------------------------ */
    var url = window.location.pathname;

    // Hide image on company description
    if(url.indexOf('/view/') >= 0) {
            $('.wp-post-image').css('display','none');
    }

/* Customizations
------------------------------------------------------------ */
    if(url.indexOf('/view/') >= 0) {
        $('td:contains("English First Tianjin")').before('<img src="" />');
    }


});

In this page:

http://goldstarteachers.com/esl-jobs-in-china/view/passionate-young-learner-teachers-wanted-in-tianjin-china/

The problem is that I can see the elements that I don't want to display for a couple of seconds.

How can I make it so that I don't see them while the page is loading?

You use css to set initial state where they are hidden and then use jQuery to display them.

So:

.wp-post-image {
  display:none;
}

is set in CSS instead of jQuery.

IMO, you should hide elements in your CSS, and do some conditional "show", rather than conditional "hide".

Do this by adding this CSS:

.wp-post-image {
  display:none;
}

and modify your javascript to this:

var url = window.location.pathname;

// Show image on company description
if(url.indexOf('/view/') == -1) {
        $('.wp-post-image').show();
}

Edit: After looking more closely, I see you call the "hide" method in $(document).ready(...) . This is why it takes longer that "expected" to hide the image. The code is not run until your page is loaded. Move the code, that hides your content OUT of $(document).ready(...) , and it should work better.

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