Accessing variables after dynamically loading a script

前端 未结 2 1565
别跟我提以往
别跟我提以往 2021-01-26 12:13

Right up front: this project doesn\'t use JQuery.

We have some third-party JavaScript; it\'s big and hairy and doesn\'t need to be used often, so we\'re dynamically loa

相关标签:
2条回答
  • 2021-01-26 12:37

    When you create a <script> element like that, you have to bind to its onload event, which is fired as soon as it's loaded and available for use.

    Another option is to just use document.write('<script src="..."></script>'); to have it loaded synchronously. Then you can use it in the following line. Just make sure to do that before the page finishes loading, or your whole document will be overwritten.

    0 讨论(0)
  • 2021-01-26 12:51

    You may try this

    function loadBigHairyCode()
    {
        var file = document.createElement('script')
        file.onreadystatechange= function () { // works in IE
            if (this.readyState == 'complete') MyFunc();
        }
        file.onload= MyFunc;
        file.type="text/javascript";
        file.src="path/to/big/ugly/script/file.js";
        document.getElementsByTagName("head")[0].appendChild(file)
    }
    
    function MyFunc(){
        //....
    }
    

    Update: You may read this.

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