javascript - Ajax 使用 CSS 加载页面

标签 javascript html css ajax

我想知道人们如何在相关时附加 CSS 以及删除 CSS。

目前我加载页面并附加到我的文档通常到其他一些 div。这通常会导致 CSS 混合到页面中,例如它看起来像这样:

<div id="parent">
   <style>
       .child {
           position:absolute;
           width: 100%;
           height:250px;
           border: 1px solid black;
        } 
   </style>

   <div class="child"></div>
</div>

虽然这行得通,但我一直被告知 CSS 应该位于页面的头部,而不是与 HTML 混合在一起。我还没有真正理解为什么,但我认为有正当理由?许多网站优化工具似乎“建议”将 CSS 放在头部,并删除未使用的 CSS。

我想知道人们如何将相关的 CSS 附加到页面头部以加载内容,然后在他们不再需要时删除所述 CSS,例如通过将内容替换为 parent 来删除它例如新的 html 页面。

有没有人这样做,或者人们只是按照我目前的方式附加?

最佳答案

I have always been told that CSS should be in the head of the page not mixed in with HTML ... website optimising tools seem to "recommend" putting CSS in the head, aswell as removing unused CSS

通常将所有 CSS 放在外部 .css 文件中要好得多,因为:

  • 大多数网站都有不止一个页面,网站中的网页使用了大部分 CSS 规则和属性,在 head 中包含 CSS 意味着您需要更改 中的某些值>head 所有网页的部分,以防您决定更改该值,而如果您的 CSS 在外部文件中,您只需在一个地方更改该值,想象一下如果您有太多网页会一团糟。
  • 如果您在每个页面中都重复了大约 50 行 CSS,那么页面大小就会增加。
  • 许多网站为其静态内容提供较长的缓存期,例如 javascript 文件、CSS 文件、字体和图像。
  • 建议将 html 保持为 html,将布局 css 与数据和 HTML 结构分开 - *对于 javascript 内联事件 onclickonmouseenter,也是如此,等等,最好将它们作为事件监听器保留在外部 .js 文件中或 script 标记之间。

实际上,网页速度建议将 CSS 放在外部文件中,除非您只有非常小的 CSS unique block ,然后将其放入 head

回到你的代码示例,我从来没有使用过这样的东西,也从未见过这样的用法,你可以将使用过的内联样式放在外部 .css 文件中,它就可以正常工作,而无需像那样包含它。

as well as removing unused CSS.

如果它未被使用,你一开始就不会编写它们,除非你正在使用像 Bootstrap、Foundation、Pure.css 等框架。正如 @Adrian Tombu 的评论所述.


来自 https://developer.yahoo.com/performance/rules.html

Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.

The key factor, then, is the frequency with which external JavaScript and CSS components are cached relative to the number of HTML documents requested. This factor, although difficult to quantify, can be gauged using various metrics. If users on your site have multiple page views per session and many of your pages re-use the same scripts and stylesheets, there is a greater potential benefit from cached external files.

关于javascript - Ajax 使用 CSS 加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34538253/

相关文章:

javascript - 如何在没有时移的情况下解析数据库中的日期字符串?

javascript - 以 Angular 路由后,数据未从 Controller 填充到 View 中

html - 如何定义 SVG viewBox 以移除可见元素周围的填充

css - IE11 : How to prevent sprite animating to correct co-ords

css - 元素出现在同一行

javascript - 通过菜单按钮滚动时 JavaScript 出现问题

javascript - 不同浏览器的不同 Jquery 值

javascript - jQuery 收集了 2 个数据点,即使只分配了一个

javascript - 如何使用 jQuery 重置或取消选择多选框?

javascript - 为什么在 D3 中将 map 不透明度设置为 0 时整个 SVG 消失了?