Running javascript after CSS is dynamically loaded and displayed

I would like to load css files dynamically and run a js script after the css is displayed in the document. I want to use an element with a new width and height that is given by the loaded css. Therefore, it is important to run js after rendering. Is it possible? I am using jQuery.

+3


source to share


2 answers


Sounds like a job for SidJS :

SidJS is a lightweight JavaScript library that allows you to include JavaScript scripts and CSS stylesheets on demand. It supports callbacks related to the download process to ensure that the resources you download are available when you need them.

In other words, you are asking for a stylesheet and providing a callback function. The callback function is executed when the stylesheet is loaded. Example:



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

      

I'm not entirely sure if the document will be redrawn by the time the callback completes, but you should try it. In the worst case, you just delay your logic by 100ms or so using setTimeout

.

+3


source


I understand your need, but I highly recommend doing this only after all alternatives have failed.

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

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



Also, if you need JS to know the styles loaded from a CSS file, JS will need to know where those files are, right? Wouldn't it be easier to provide this information instead of the file url?

It's hard to think about alternatives without knowing exactly why you know which file to download after the page loads. If it is 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 the element classes, so removing the class styles and applying the new class styles to it.

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

+1


source







All Articles