有没有一种方法只能在服务器响应中发送匹配的媒体查询?

时间:2018-12-05 23:50:25

标签: css optimization server

我有大量的移动CSS和大量的台式机CSS,当只有一半的媒体查询与任何给定的客户端匹配时,我不想同时发送它们。

有没有办法预先确定哪些媒体查询将匹配并仅发送那部分CSS?

1 个答案:

答案 0 :(得分:0)

此问题与响应式设计一样古老。最简单(但最不正确)的方法是使某种空白页面加载设备的样式和内容。这是不正确的,因为它面对可访问性,可爬网性(机器人)和用户体验(与服务器端呈现的网站相比,页面加载时间更长)会吐出来。

我过去解决此问题的方法是将网站/应用分为三部分

  1. “外壳”(页眉,导航,页脚,总体布局)
  2. “肉”(用户和搜索引擎想要的内容)
  3. 其他所有内容(广告,辅助功能,非关键内容)

您要在服务器上呈现“外壳”和“肉”以及一组最少的样式,以使其在不进行任何额外请求的情况下呈现某些内容。这些样式应包括最少的@media个查询集,以粗略响应的方式呈现网站/应用。

接下来,使用页面中嵌入的JavaScript,您要隐藏网站的“内容”,使其不可见。您想要显示一个加载指示器,以便用户知道您正在加载某些东西。 “外壳”应始终可见,因为这使用户感觉到您的网站已处于加载的一半。此时,您可以加载剩余的样式和内容。

一旦样式和其他内容被加载,您可以隐藏加载器并显示您的样式内容。此时,您可以加载任何非关键内容或广告。这是基本布局:

<head>
  <style>
    /* 
    include core styles and base media queries 
    for high-level layout and theming
    */

    html,
    body,
    main {
      height: 100%;
    }

    /* include loader styles here */
    .loader {
      height: 100%;
      background-color: #fff;
    }
  </style>
</head>

<body>
  <header>
    <img src="logo.png" />
    <nav>Home | About | Sign In</nav>
  </header>

  <main>
    <script>
      // use JavaScript to show the loader and hide the main content
        document.write('<div class="loader">/* spinner gif */</div>');
    </script>

    <!-- Meat of the page - initially hidden by the loader -->
  </main>

  <footer>
    <!-- Footer content -->
  </footer>

  <script>
    /* 
    Load the rest of your app here. This should include
    styles for the current device, extra content, etc.

    After the styles and content are loaded, hide the loader
    so the user can start using the site/app. At that point
    start loading ads and other non-critical content.
    */
  </script>
</body>