Daniel Bengtsson Daniel Bengtsson - 2 months ago 7
CSS Question

I'm trying to load a js and a css file from within a javascript

I'm trying to load a js and a css file from within a javascript in chrome I can see that both files are loaded, the mofo alert is triggered, and then the test alert, but not the test2 alert.

Why is that, is there an error in the javascript I can't see?

function loadScript(url, callback){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
document.getElementsByTagName('script')[0].appendChild(script);
}

function loadCss(url, callback){
var elem = document.createElement('link');
elem.href = url;
elem.type = 'text/css';
elem.rel = 'stylesheet';
elem.media = 'all';
document.getElementsByTagName('script')[0].appendChild(elem);
}

var coptaJQStart = function() {
var jQuery_1_11_3 = $.noConflict(true);
alert('test');
};

var coptaCssStart = function() {
alert('test2');
};


loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', coptaJQStart);
loadCss('http://www.tffan.com/copta.css', coptaCssStart);
alert('mofo');

Answer

You have to attach call back function in loadCss

 elem.onreadystatechange = callback;
    elem.onload = callback;

function loadScript(url, callback){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.onreadystatechange = callback;
    script.onload = callback;
    document.getElementsByTagName('script')[0].appendChild(script);
}

function loadCss(url, callback){
    var elem = document.createElement('link');
    elem.href = url;
    elem.type = 'text/css';
    elem.rel = 'stylesheet';
    elem.onreadystatechange = callback;
    elem.onload = callback;
    elem.media = 'all';
    document.getElementsByTagName('script')[0].appendChild(elem);
}

var coptaJQStart = function() {
    var jQuery_1_11_3 = $.noConflict(true);
    alert('test');
};

var coptaCssStart = function() {
    alert('test2');
};


loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', coptaJQStart);
loadCss('http://www.tffan.com/copta.css', coptaCssStart);
alert('mofo');