Middle
What is the connection of style flickering in web applications?
sobes.tech AI
Answer from AI
Flash of Unstyled Content (FOUC) occurs when the browser first displays the page content without styles applied, then applies them. This is related to the order of resource loading and processing.
Main causes:
- CSS loads slower than HTML: The browser starts parsing and rendering HTML before CSS is fully loaded and processed.
- Styles are declared after content: If
<link>or<style>tags are placed after<script>or main HTML content in the<body>section, the browser will start rendering before processing them. - @import in CSS: The
@importdirective causes the browser to load additional CSS files sequentially, blocking style rendering until all imports are completed. - JavaScript modifying styles: Scripts that dynamically load or apply styles after the initial page load can cause FOUC.
- Third-party resources: Slow loading fonts or other resources needed for styles can temporarily display the page without them.
Ways to prevent:
- Place
<link rel="stylesheet">in<head>: This ensures CSS starts loading and processing as early as possible. - Use inline styles for critical CSS: A small amount of critical styles needed for initial display can be embedded directly in a
<style>tag in<head>. - Avoid
@import: Prefer using multiple<link>tags. - Optimize JavaScript loading: Deferred or asynchronous script execution (
defer,async) can help if they do not affect initial styles. - Preload fonts: Using
<link rel="preload">for important fonts can reduce FOUC related to fonts.
<!-- Example of correct CSS placement -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<link rel="stylesheet" href="styles.css">
<style>
/* Critical styles */
body { opacity: 1; }
</style>
</head>
<body>
<!-- Content -->
</body>
</html>