开发者

jQuery, CSS - when to use addClass function after page load

开发者 https://www.devze.com 2023-03-26 06:51 出处:网络
I have an html element with class i.e article: <article> Content </article> For my jQuery script it means, that it should add some specific classes prepared before:

I have an html element with class i.e article:

<article> Content </article>

For my jQuery script it means, that it should add some specific classes prepared before:

$('article').addClass('rounded box-shadow gradient-bright');

I have some article and other similiar boxes around whole my web page, so if I want to change开发者_开发知识库 something I have to do it only in one place - javascript script.

But the question is, how I should use jQuery to get the best results? I don't want situation that user have to see changes on loaded page (i.e slow transfer so at the beginning is box, then he see it's rounded box with shadow... he should definitely see all changes at once).

So...

$(window).ready( /* add class */ ) ...

Or...

$(document).ready( /* add class */ ) ...

Or...

Without ready function , just /* add class */

Or maybe there is any other solution?

Edit Change <div class="article"> into <article> pro forma ;) But it's only example...


You should be using the document-way. This means the codes will get executed at the earliest possible moment after the DOM has been built.

To expand on this: window ready also waits for external source to be loaded (images, etc).


You can try something like

jQuery('html').addClass('prepStyles');

and add styles to those elements you need to style like

.prepStyles .article {
    /*  your styles to make the article look nice, resembling .rounded.box-shadow.gradient-bright */
}

This will load those .article elements with required styles right away. But then, in order to make things clean, you can do your

$(document).ready(function () {
    $('.article').addClass('rounded box-shadow gradient-bright');
});

That will re-apply the already-defined styles from .prepStyles .article and, now you can remove that class from :

$(document).ready(function () {
    …
    jQuery('html').removeClass('prepStyles');
});


Avoiding the FOUC (flash of unstyled content) - this article by Paul Irish may help you. As ikanobori refers to and using Pauls technique it may be useful to clear the js class on window ready if your css relies on background images. Only at this time can you be sure these have all been loaded.


The best thing to do here is to $(document).ready( /* add class */ ) ... because the document is smaller than the window

or even better, make sure it's served styled from your server

0

精彩评论

暂无评论...
验证码 换一张
取 消