RobbeR
RobbeR

Reputation: 485

Run javascript after CSS is dynamically load and rendered

I would like to load css files dynamically, and run a js script after the css is rendered on the document. I want to use an element's new width and height which is set by the loaded css.. So it's important to run the js after render. Is it possible? I'm using jQuery.

Upvotes: 5

Views: 2096

Answers (2)

Hikari
Hikari

Reputation: 3947

I understand your need, but I highly recommend to do it only after all alternatives fail.

How many CSS files do you have? how different are they?

It would even be better to set styles in JS rather than using it to load CSS files.

Also, if your need is for JS to know styles loaded from the CSS file, JS will need to know where those files are, right? Isn't it easier to provide those info instead of the file URL?

It's hard to think on alternatives without knowing why exactally you'll only know which file to load after page has loaded. If it's based on some user input, you can just have a CSS file with different styles for a set of classes, and use JS to change element classes, therefore removing a class styles and applying new class styles to it.

Always try to keep all your styles on a unique file, trying to keep it organized and compact, reusing always possible. Then you use JS to change styles, classes and elements as needed.

Upvotes: 1

Hubro
Hubro

Reputation: 59323

Sounds like a job for SidJS:

SidJS is a lightweight JavaScript library that allows one to include JavaScript scripts and CSS stylesheets on demand. It supports callbacks tied to the loading process to guarantee that the resources you're loading are available when you need them.

In other words, you request a style sheet and provide a callback function. The callback function is executed when the style sheet has been loaded. Example:

Sid.css("my-sheet.css", function() {
    // Perform your width/height logic here.
});

I'm not completely sure if the document will have had time to redraw by the time the callback is executed, but you should try it out. Worst case scenario, you simply delay your logic by 100ms or so using setTimeout.

Upvotes: 3

Related Questions