Problems with dynamic loading in JavaScript

后端 未结 3 720
执笔经年
执笔经年 2021-01-05 21:47

I am a JavaScript newbie and learn by working on a pure JavaScript \"project\" that calculates mathematical functions. It all works well. Now, as a further step, I

3条回答
  •  孤城傲影
    2021-01-05 22:30

    How to dynamically load a script file (the most basic version, also there are multiple options to this):

       function loadScriptFile(scriptPath, jsFile, callBack)
       {
           var scriptTag = document.createElement("script"); //creates a HTML script element
           scriptTag.language = "JavaScript"; //sets the language attribute
           scriptTag.type = "text/javascript";
           scriptTag.src = scriptPath + jsFile + ".js"; //the source
           if (callBack)
           {
                scriptTag.onload = callback; //when loaded execute call back
           }
           var scriptTagParent = document.getElementsByTagName("script")[0];
           if (scriptTagParent)
           {
                    scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
           }
           else
           {
               document.body.appendChild(scriptTag);
           }
        }
    

    How it works:

    Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).

    The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.


    Just a basic example of what I meant in my comment:

    This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)

    XML-file: language.xml Basic XML structure:

    
        
            
                
            
        
        
            
                
            
        
    
    

    What did I do:
    I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.

    Now the loading will be done by AJAX:

    var xmlLoader = new XMLHttpRequest();
    xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
    xmlLoader.open("get", "language.xml", true); //set asynchronous to true
    xmlLoader.send(null);
    
    function trackRequest()
    {
       if (this.status == 200 && this.readyState == 4) //all is good
       {
          globalLanguageFile = this.responseXML;
          startProgram(); //fictive function that starts your program
       }
    }
    

    Now the XML is loaded. How to load strings from it?

    function loadLanguageString(code, id, fallback)
    {
        var word = fallback;  
        if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
        {
            if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
            {
                //found the correct language tag and id tag. Now retrieve the content with textContent.
                word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
            }
        }
    
        return word; //when failed return fall back string
    }
    

    How to call the function:

    loadLanguageString(1031, 1000, "Hello World!");
    

提交回复
热议问题