使用 javascript/jQuery 重新加载样式表而不闪烁未设置样式的内容

Reloading stylesheet without flashing of unstyled content using javascript/jQuery

问题背景

我正在开发一个网页,用户可以在其中动态更改和设置自定义水平菜单的样式。所以有一堆样式设置(高度、填充等...)和页面顶部的预览。当他们更改这些设置时,我重新加载菜单的 html 和 css,以便它具有新的值。

问题

如下所示,我正在加载 html,完成后,我将应用 html 并重新加载 css。这一切都有效。但是,在大多数情况下,html 会在没有任何样式的情况下闪烁。我相信这是在重新生成 css 时发生的。我需要防止这种情况。

如何在没有样式的情况下重新生成样式表,同时防止出现时间上的小差距?

$.get("http://www.url1.com", function(html) {
    // add the new html
    $(".preview-section").html(html);

    // reload stylesheet
    var timestamp = Math.round(+new Date()/1000);
    $("head").append($("<link/>", { rel: "stylesheet", href: "http://www.url2.com?cache="+timestamp, type: "text/css" }));
});

您可以先 ajax 调用 http://www.url2.com?cache="+timestamp。 然后在它的回调中,首先将 link 附加到头部,它应该立即加载样式表,因为它是在那个时候缓存的。 最后更新您的预览部分 html.

$.get("http://www.url1.com", function(html) {

   var timestamp = Math.round(+new Date()/1000);

   $.get("http://www.url2.com?cache="+timestamp, function() {
      // stylesheet is now cached in the browser
      // reload stylesheet
      $("head").append($("<link/>", { rel: "stylesheet", href: "http://www.url2.com?cache="+timestamp, type: "text/css" }));

      // add the new html
      $(".preview-section").html(html);
   });

});

这一切都假设您可以控制 url2.com 的交叉原点设置。

您也可以使用 lazyload js.

我检查了它的作用,发现它在 header:

中添加了带有 css 导入的内联样式
<style class="lazyload" charset="utf-8">

    @import "http://maxcdn.bootstrapcdn.com/bootstrap/…

</style>

也许你也可以手动添加这个 with-out lazyload,但我还没有检查是否可行。

请看这个SO question。在那里我找到了 lazyload 的技巧。

lazyload 的工作演示在下方和此处 jsFiddle

(我没有对内容使用 ajax 调用,因为那应该不是问题。只需在 ajax 的 done 回调中调用 lazyload,它应该可以工作。)

$(function () {

    var addContent = function () {
        var $well = $('<p class="well"/>')
            .text('This is stlyed by bootstrap');
        $('.preview-section').html($well);
    };

    $('#addNewButton').click(function () {
        // Load a CSS file and pass an argument to the callback function.
        LazyLoad.css('http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css', function (arg) {
            // put your code here
            addContent();
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazyload/2.0.3/lazyload-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addNewButton">Add element with stlye from external stlyesheet</button>
<div class='preview-section'></div>