Bootstrap-select plugin: how to avoid flickering

血红的双手。 提交于 2019-12-05 00:34:21

To show a blank until bootstrap-select is loaded, add this to your css.

select {
   visibility: hidden;
}
KyleMit

There's not a great way to prevent the flickering all together, but you can minimize it.

The problem is that in addition to whatever other bottlenecks you have, you have to download and parse a lot of javascript files first. Bootstrap-Select depends on Bootstrap which itself depends on jQuery. By the time all that javascript is loaded, the page is probably already rendered.

One thing you can do to minimize the flickering is to style the select elements as similar to the final product as possible so they take the same amount of screen space. When the plugin loads, it will hide this control anyway and replace it with it's own implementation. Use the selector that you were going to pass into the selectpicker() function and style like this:

.selectpicker {
    width: 220px;
    height:34px;
    margin-bottom: 10px;
}

Working Demo in fiddle

Note: I've intentionally delayed the load time by using setTimeout so the difference is more noticeable.

setTimeout(function() { $(".selectpicker").selectpicker(); }, 500);

If that's really still not acceptable, you can display a loading graphic until the page is fully loaded.
Adapted from Loading screen example:

Add this to your HTML:

<div id="loader"></div> 

Style it like this in CSS:

#loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('http://i.imgur.com/ntIrgYXs.gif') 50% 50% no-repeat grey;
}

And remove it with the following JavaScript after you've loaded your page:

$("#loader").fadeOut("slow");

Working Demo Of Loading Screen In Fiddle

Use size to limit the height of the select, before it is being replaced:

<select size="1">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
</select>

The spec around this attribute says:

'size' Defines the number of visible options in a drop-down list

This solution works for me:

<select class="selectpicker">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
</select>

<script>
    $('.selectpicker').selectpicker({  
        width: '100%'
    });
</script>

I just place the script right after the creation of the select drop-down, instead of waiting for the document to be ready!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!