简体   繁体   中英

When loading css from a javascript file, how should I keep the html output hidden until the css file is loaded?

When javascript creates the parent div that all of my output is contained in, I am hiding it with element.style.display = 'none' . For performance purposes, I think having my plugin (javascript) load the css file at the beginning is the fastest way. Then the css will make the parent div visible again once it loads. However, if the css file loads before the div is created, wouldn't javascript still hide it when it gets to that point in the code? Using an !important tag here would seem cheap. Alternatively, loading the css file after creating the div would just mean the output would take longer to be displayed to the user. I'm wondering if there is a standard solution to this, but haven't been able to find one. Thanks!

<style>
   body { display: none; }
</style>
<script>
   window.onload = function(){ document.body.style.display = null; }
</script>

You might check whether the CSS link ref is loaded, that's higher level, but I recommend the JavaScript book by David Flanagan.

Better way is to use pure CSS - it happens automatically and doesn't wait for document load.

<style>
   body { display: none; }
</style>
<link rel="stylesheet" href="some.css">

In some.css file:

body { display: inherit; }

Not sure about inherit , maybe block will work. Try.

When you create the wrapper DIV, give is a class name of something like "hideMe", and have a definition of hideMe as display:none . When you want to show it, remove the class (or redefine it).

you can use jQuery and solve this with:

$(document).ready( function() {
   $(element).show();
});

or

$(window).load( function() {
   $(element).show();
});

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