【问题标题】:How to asynchronously load CSS using jQuery?如何使用 jQuery 异步加载 CSS?
【发布时间】:2011-07-08 09:11:02
【问题描述】:

我想使用 jQuery 为文档异步加载 CSS。

我找到了这个示例,但这似乎在 IE 中不起作用:

<script type="text/javascript" src="/inc/body/jquery/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        $('<link>', {
            rel: 'stylesheet',
            type: 'text/css',
            href: '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css'
        }).appendTo('head');
        $.getScript("/inc/body/jquery/js/jquery-ui-1.8.10.custom.min.js", function(){
        });
    });
</script>

基本上我想在所有其他数据、图像、样式等加载到页面后加载jQuery UI

$.getScript 非常适合 JS 文件。唯一的问题是 IE 中的 CSS。

你知道更好的解决方案吗?

【问题讨论】:

  • 如果你把它做成$('&lt;link/&gt;'...,它会起作用吗? IE。添加正斜杠。
  • 我不确定您所说的异步是什么意思...您可能是指动态的吗?

标签: jquery css jquery-ui asynchronous


【解决方案1】:

这应该在 IE 中工作:

$("head").append("<link rel='stylesheet' type='text/css' href='/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css' />");

【讨论】:

  • 反之亦然:$('&lt;link .../&gt;').appendTo($('head'))。这将允许您链接 link 元素,而不是 head 元素,如果您想在将其附加到 &lt;head&gt; 后对其执行其他操作。
  • 据此 (stackoverflow.com/questions/5085228/…),追加不会异步执行。
  • @ElHaix 确实如此,但我认为 OP 误解了“异步”这个词,真正的意思是“动态”。
  • @PeterOlson - 查看yterium.net/jQl-an-asynchronous-jQuery-Loader - 你真的可以加载你的 CSS 异步吗?
  • 对,这不是异步的。
【解决方案2】:

安全的方式是旧的方式......

var stylesheet = document.createElement('link');
stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(stylesheet);

【讨论】:

  • 谢谢,但我更喜欢在 jQuery 中执行此操作。
  • 为什么这比 jQuery 更可取?你提到这是“安全”的方式。是什么使它比公认的答案更安全(当然假设存在 jQuery)?
  • RequireJS.org 文档专门参考了这种方法:requirejs.org/docs/faq-advanced.html#css
  • 根据经验:纯 JS 总是更好,但我不明白这个解决方案如何解决不知道 CSS 文件何时完成加载的问题。
  • 让我告诉你为什么这种方法比 jQuery 更有效...因为如果你通过 jQuery 加载它,你将不得不等到 jQuery 被加载,但使用这种方法你不需要等待jQuery,你可以并行加载jQuery、CSS和其他脚本
【解决方案3】:
jQuery(function(){

jQuery('head').append('<link href="/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css" rel="stylesheet" type="text/css" />')

});

【讨论】:

    【解决方案4】:

    正如RequireJS docs 中提到的,棘手的部分在于加载 CSS:

    function loadCss(url) {
        var link = document.createElement("link");
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = url;
        document.getElementsByTagName("head")[0].appendChild(link);
    }
    

    但要知道 CSS 何时/是否已成功加载,例如在您的用例中“我想在所有其他数据、图像、样式等加载之后加载 jQuery UI”。

    理想情况下,RequireJS 可以加载 CSS 文件作为依赖项。然而,有 是知道何时加载 CSS 文件的问题,尤其是在 从另一个域加载文件时的 Gecko/Firefox。一些 历史可以在这张道场门票中找到。

    知道文件何时加载很重要,因为您可能只想 获取样式表后的 DOM 元素的尺寸 已加载。

    有些人实施了一种寻找井的方法 要应用于特定 HTML 元素的已知样式,以了解是否有 样式表已加载。由于该解决方案的特殊性,它是 不适合 RequireJS 的东西。知道什么时候 链接元素已加载引用的文件将是最健壮的 解决方案。

    由于知道文件何时加载是不可靠的,所以它不 在 RequireJS 加载中显式支持 CSS 文件是有意义的,因为 由于浏览器行为,它会导致错误报告。

    【讨论】:

      【解决方案5】:

      根据Dynamically loading css stylesheet doesn't work on IE

      您需要最后设置 href attr 并且仅在将链接 elem 附加到头部之后。

      $("<link>")
        .appendTo('head')
        .attr({type : 'text/css', rel : 'stylesheet'})
        .attr('href', '/css/your_css_file.css');
      

      【讨论】:

        【解决方案6】:
        $.get("path.to.css",function(data){
            $("head").append("<style>"+data+"</style>");
        });
        

        【讨论】:

        • 警告:如果您的 css 文件是跨域托管的(浏览器限制),这可能不起作用。
        • ^ 对于每个 http 请求都是如此
        【解决方案7】:

        这里没有一个解决方案实际上是在不阻塞页面渲染的情况下加载 CSS 文件——这通常是“异步”的意思。 (如果浏览器正在等待某事并阻止用户与页面交互,则根据定义,这种情况是同步的。)

        同步和异步加载的例子可以在这里找到:

        http://ajh.us/async-css

        我发现使用setTimeout 来延迟加载似乎有帮助。

        【讨论】:

          【解决方案8】:

          这是一种异步样式表加载方法,它不会阻止页面呈现,它对我有用:

          https://github.com/filamentgroup/loadCSS/blob/master/loadCSS.js

          上面链接的代码的简化示例,基于 lonesomeday 的回答

          var stylesheet = document.createElement('link');
          stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
          stylesheet.rel = 'stylesheet';
          stylesheet.type = 'text/css';
          // temporarily set media to something inapplicable to ensure it'll fetch without blocking render
          stylesheet.media = 'only x';
          // set the media back when the stylesheet loads
          stylesheet.onload = function() {stylesheet.media = 'all'}
          document.getElementsByTagName('head')[0].appendChild(stylesheet);
          

          【讨论】:

          • !!这对我来说最有效(考虑到 pageSpeed 洞察)
          • 像魅力一样工作!
          猜你喜欢
          • 1970-01-01
          • 2018-09-18
          • 2011-05-16
          • 1970-01-01
          • 2018-04-04
          • 2011-04-24
          • 2014-09-06
          • 2015-04-08
          相关资源
          最近更新 更多