JS脚本动态加载不一致

时间:2015-08-24 19:39:21

标签: javascript jquery html5 loading

我需要帮助才能使一些动态js加载正常工作。我现在遇到的问题是,在加载页面时,它并没有始终如一地加载js脚本。这是我在页面底部打开的脚本:

function getJSOnload() {
    var element;
    var parent = document.body;
    var cdn = [
                LoadFormValidationScript(LoginFormValidator),
                LoadFormValidationScript(SetFormLocaleLang)
            ];
    var i = 0, file;
    for (i;i<cdn.length;i++) {
        file = cdn[i];
        element = document.createElement("script");
        element.type = "text/javascript";
        element.src  = file;
        parent.appendChild(element);
        //free file's value
        file = null;
    }
};
    if (window.addEventListener) {
        window.addEventListener("load", getJSOnload(), false);
    }
    else if (window.attachEvent) {
        window.attachEvent("onload", getJSOnload());
    }
    else window.onload = getJSOnload();

这是我在外部js文件中的LoadFormValidationScript

function LoadFormValidationScript(callback){

    function LoadValidationScripts() {

        $.getScript('/plugins/script1.min.js', function() {
            $.getScript('/plugins/script2.min.js', function() {
                $.getScript('/plugins/script3.addons.min.js', function() {
                    $.getScript('/plugins/script.es_ES.js', function() {
                        $.getScript('/plugins/script4.fr_FR.js', function() {
                            $.getScript('/plugins/script5.de_DE.js', callback);
                        });
                    });
                });
            });
        });
    }
    if (!$.fn.formValidation){
        LoadValidationScripts();
    } else {
        if (callback && typeof(callback) === "function") {
            callback();
        }
    }
}

这是&#34; setFormLocaleLang&#34;作为一个例子,因为它很短

function SetFormLocaleLang(){

    var nberOfForm = document.forms.length; //get number of forms on the page

    // if there are no forms in the page don't waist your time
    if (nberOfForm > 0) {
        var Locale = "en_US"; //default formVlaidation language
        //var lang =  $('html').attr('lang'); // get the page language
        var lang = $("#selectedLanguage").attr('data-lang-id');

       // assign the Locale depending on page language
        switch (lang) {
            case "en" : Locale = 'en_US'; break;
            case "fr" : Locale = 'fr_FR'; break;
            case "es" : Locale = 'es_ES'; break;
            case "de" : Locale = 'de_DE'; break;
            default : break;
        };
        //set the locale for all the forms in the page
        for (var i = 0; i < nberOfForm; i++) {
            var strFormID = "#" + document.forms[i].id;
            $(strFormID).formValidation('setLocale', Locale);
        }
    }
}

就像是说它确实可以工作并加载脚本但不是所有的时间,有时我必须像3次一样刷新页面以加载脚本,有时我会在打开页面时第一次尝试加载。不知道发生了什么以及为什么我会这样做。

0 个答案:

没有答案