Dynamically reload local Javascript source / json data

后端 未结 2 1739
野趣味
野趣味 2020-12-11 10:01

What are the possible cross browser (at least Firefox & Chrome) methods to dynamically reload a local Javascript file that is referenced by a locally loaded html file?

相关标签:
2条回答
  • 2020-12-11 10:37

    If your app starts up Chrome then you can include the --allow-file-access-from-files flag in the start command.

    0 讨论(0)
  • 2020-12-11 10:46

    I use the following code to reload JavaScript and JSON files.

    /* Load a JavaScript or JSON file to use its data */    
    function loadJsFile(filename, dataIsLoaded){
        var fileref = document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
        fileref.onload = dataIsLoaded;
    
        if (typeof fileref!="undefined"){
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }  
    }
    
    /* The callback that is invoked when the file is loaded */
    function dataIsLoaded(){
        console.log("Your data is ready to use");
    }
    

    Usage when the JSON file is in the same directory as the website:

    var jsonFile= "myData.json";
    loadJsFile(jsonFile, dataIsLoaded);
    

    I tested it successfully in IE10 and Firefox 22; it doesn't work in Chrome though.

    0 讨论(0)
提交回复
热议问题