我试图从javascript中加载js和css文件

时间:2016-09-09 18:56:17

标签: javascript jquery css

我试图从Chrome中的javascript中加载js和css文件我可以看到两个文件都已加载,mofo警报被触发,然后是测试警报,但不是test2警报。

为什么会这样,我无法看到javascript中的错误?

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');

1 个答案:

答案 0 :(得分:1)

您必须在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');