jQuery.ready() function and asynchronous CSS

2019-07-11 17:23发布

I want to load my website CSS asynchronously. I want to know if jQuery.ready() function will run after the async load of the CSS is completed or will jQuery ignore it and the CSS might finish loading after jQuery.ready() function starts running.

3条回答
smile是对你的礼貌
2楼-- · 2019-07-11 18:06

jQuery.ready() runs when the DOM has been loaded.

If you wish to load some CSS asynchronously, then your best bet would be to insert link tag in the head in the ready callback.

In other words...

<script language="javascript">
   $(document).ready(function()
    {
         $("head").append("<link rel=stylesheet href='yourfile.css' type='text/css'/>");
    }
   )
</script>

Hope it helps!

查看更多
Root(大扎)
3楼-- · 2019-07-11 18:13

Try utilizing $.holdReady()

// set `$.holdReady()` to `true`
$.holdReady(true);
// do stuff at `$.holdReady(true)`
// e.g., call hide `body` element
$("body").hide();
// load asynchronous `css`
$("<style>")
.appendTo("head")
.load("https://gist.githubusercontent.com/anonymous/ec1ebbf8024850b7d400/"
      + "raw/906431c0472286e141b91aac1676369bbb8d2f97/style.css"
      , function(e) {
  // set `$.holdReady()` to `false`
  $.holdReady(false);
});
// do stuff at `$.holdReady(false)`
$(document).ready(function() {
  $("body").show();
  alert("ready");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
  <div>
    abc
  </div>
    <div>
    123
  </div>
</body>

查看更多
一夜七次
4楼-- · 2019-07-11 18:24

Short answer - no. $(document).ready() will not wait for asynchronous loading to finish. It will fire as soon as DOM is loaded.

Normally you would put async loading functions inside (document).ready() so they start executing as soon as they safely can. It's a little weird that you're trying to perform async CSS loading before the DOM. $(document).ready() is an event-trigger function. It's cannot be made to wait.

Please elaborate on what exactly you are trying to accomplish.

P.S. Please read this "execution sequence" answer: Load and execution sequence of a web page?

查看更多
登录 后发表回答