Matt Way
Matt Way

Reputation: 33161

Dynamically loading CSS in angularjs (loading delay)

I am using two visual templates for a particular site, whose css conflicts quite a bit, so rather than doing a painful edit, I figured dynamic loading would do the trick.

So I use this in my <head>

<!-- css is loaded dynamically through angular -->
<link ng-repeat="item in css.files" ng-href="{{item}}" rel="stylesheet">

And set $rootScope.css.files inside my .config() of my module.

The CSS loads fine, however there is a noticeable delay between loading the page content, and loading the CSS. Basically the unstyled html displays for a moment until the CSS files have completely loaded.

Is there any way to stop the page showing before the CSS has loaded? Is there any event for load completion of an ng-href item?

Upvotes: 1

Views: 2024

Answers (2)

jgawrych
jgawrych

Reputation: 3542

The easiest way will be to just use plain old css.

In the header of your page add this:

<style>
  html, body {
    display: none;
  }
</style>

Then in the last css to load, undo the display none:

  html, body {
    display: block;
  }

The latter will override the previous, and your page will appear with all of your dynamic css.

Upvotes: 2

Jeff Hubbard
Jeff Hubbard

Reputation: 9892

The problem here is that you're revealing the content before the CSS files have downloaded. I don't know offhand if the HTMLLinkElement object has an event for when it's loaded, but basically you need to wait for your CSS to download before revealing the content. Using ng-cloak here won't help because ng-cloak hides the content while angular is loading, not while other files are loading.

Upvotes: 0

Related Questions