Javascript, execute scripts code in order inserted into dom tree

前端 未结 5 1523
囚心锁ツ
囚心锁ツ 2021-01-06 05:47

NOT A DUPLICATE AS I HAVE YET TO FOUND A SATISFYING ANSWER ON OTHER THREADS:

  • Load and execute javascript code SYNCHRONOUSLY
  • Loading HTML and Script o
5条回答
  •  自闭症患者
    2021-01-06 06:25

    I am posting here just like a draft
    This do not work because cross-domain police
    Here the idea is to obtain all scripts first and when they are in memory, execute them in order.

    function loadScript(order, path) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET",path,true);
        xhr.send();
        xhr.onreadystatechange = function(){
            if(xhr.readyState  == 4){
                if(xhr.status >= 200 && xhr.status < 300 || xhr == 304){
                    loadedScripts[order] = xhr.responseText;
                }
                else {
                    //deal with error
                    loadedScripts[order] = 'alert("this is a failure to load script '+order+'");';
                    // or  loadedScripts[order] = '';  // this smoothly fails
                }
                alert(order+' - '+xhr.status+' > '+xhr.responseText);                // this is to show the completion order.  Careful, FF stacks aletrs so you see in reverse.
                // am I the last one ???
                executeAllScripts();
            }
        };
    }
    
    function executeAllScripts(){
        if(loadedScripts.length!=scriptsToLoad.length) return;
        for(var a=0; a

提交回复
热议问题