Link to home
Start Free TrialLog in
Avatar of maccaj51
maccaj51Flag for Afghanistan

asked on

Javascript after load css

Hi Experts,

I am currently using the code below to load my css files in (as per google pagespeed guidelines). One of my plugins relies on the css being loaded before it fires. Its a background image plugin.

Is there anyway of setting the code up so the plugin only runs once this has completed?

Thanks in advance

var loadCss = function() {
    var links = ["///fonts.googleapis.com/css?family=Open+Sans:400,600,700", "/core.css", "/main.css"],
        headElement = document.getElementsByTagName("head")[0],
        linkElement, i;
    for (i = 0; i < links.length; i++) {
        linkElement = document.createElement("link");
        linkElement.rel = "stylesheet";
        linkElement.href = links[i];
        headElement.appendChild(linkElement);
    }
};
var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) {
    raf(loadCss);
} else {
    window.addEventListener("load", loadCss);
}

Open in new window

Avatar of Hans Langer
Hans Langer

I would add an Hidden HTML element, like a div: <div id="cssflag" /> and then evaluate with javascript to see if the css has been loaded:

css file:
#cssflag{display:none}

Open in new window

javascript:
setTimeout(function(){
    if(!$('#cssflag').is(':visible') ){
       //loadJS()
    }
},100)

Open in new window

Avatar of Julian Hansen
Why not load the plugin dynamically as well and put the code to do so after your CSS load?
Avatar of maccaj51

ASKER

Hi Julian,

Could you give me an example?
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thats great Julian - Thanks ever so much!!

I'm awarding you the points but just wondering if I could ask u if i need:

var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) {
    raf(loadCss);
} else {
    window.addEventListener("load", loadCss);
}