0

I found a HTML5 way of changing a class of an element using JavaScript.

HTML:

<div id="bootstrap-container" class="container-fluid fill-height">
   <!-- Content -->
</div>

JavaScript:

var mql = window.matchMedia('(min-width: 1200px)');
if (mql.matches) {
    var containerElement = document.querySelector('#bootstrap-container');
    if (containerElement.classList.contains('container-fluid')) {
        containerElement.classList.remove('container-fluid');
        containerElement.classList.add('container');
    }
}

This works fine except there is a noticeable FOUC when loading/refreshing the page.

How can I make the FOUC go away?

3
  • 2
    I expect any styling that relies on JS will have the potential for a FOUC, this looks like something you could potentially do with just a CSS media query, which is generally less prone to creating a FOUC. Commented Aug 5, 2016 at 16:13
  • Agreed, but in this case the built-in container class in bootstrap contains a lot of styles which would have to be overriden in a media-query block in the stylesheet and that is not an easy thing to do. Commented Aug 5, 2016 at 16:20
  • @DBS generally speaking you're right, but there are some (valid) cases/logic, which can't be covered by media queries. Commented Aug 5, 2016 at 16:22

2 Answers 2

1

When the browser parses your HTML-File, he will execute your JavaScript (either inline or by reference <script src="script.js">) exactly where he found it. Therefore you have 2 possibilities to avoid the mentioned FOUC.

  1. You execute the JavaScript earlier (e.g. as inline javascript right below the element you manipulate the class). It might be a good idea to set only 1 "media query class" (e.g. on the body-tag) and place your corresponding script right below

  2. You hide the content until your JavaScript has been executed. E.g. you could do something like this

HTML

<body class="loading">
 ...
</body>

CSS

body.loading {
  visibility: hidden;
} 

JS

var mql = window.matchMedia('(min-width: 1200px)');
if (mql.matches) {
    var containerElement = document.querySelector('#bootstrap-container');
    if (containerElement.classList.contains('container-fluid')) {
        containerElement.classList.remove('container-fluid');
        containerElement.classList.add('container');
    }
}

document.body.classList.remove("loading")
Sign up to request clarification or add additional context in comments.

Comments

0

I solved it by creating a partial view and using bootstraps responsive utility classes hidden-xs, hidden-sm and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.