且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态加载脚本后访问变量

更新时间:2023-12-04 23:42:52

你可以尝试这个

  function loadBigHairyCode()
{
var file = document.createElement('script ')
file.onreadystatechange = function(){//在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)
}

函数MyFunc(){
// ....
}

更新: 您可以阅读此


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 loading it only when we need to:

function loadBigHairyCode()
{
    var file = document.createElement('script')
    file.setAttribute("type","text/javascript")
    file.setAttribute("src","path/to/big/ugly/script/file.js")
    document.getElementsByTagName("head")[0].appendChild(file)

    magic_needs_to_happen_here
}

The script loading works fine, including some corresponding CSS that's not shown here.

The loaded file defines a constructor function (call it UglyGlobalFunc) which we use elsewhere in the usual way (var foo = new UglyGlobalFunc(....)). The problem is, because the rest of that file is kinda ugly, we need to fix it up a bit so that it sucks less. Specifically, at the point where I've shown "magic needs to happen here" above, I want to write the equivalent of

UglyGlobalFunc.prototype.BodgeBodgeBodge = function() {....}

just as if I were editing the underlying file.

But that fails, because at that point in the code, UglyGlobalFunc is undefined, which makes sense. Same for a simple level of indirection like window.UglyGlobalFunc.proto.... So my questions are:

  1. Are the dynamically loaded contents even accessible at that point of execution (where magic needs to happen)? Or do they not become "real" until after loadBigHairyCode() returns and the browser goes through some kind of refresh cycle?

  2. If yes, then how do I access them? Some kind of getGlobalVariableByName("string") function?

  3. If not, then... aieee. How do normal sane people go about doing that kind of thing?

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.