How do you dynamically load a javascript file from different domain?

前端 未结 3 1960
小鲜肉
小鲜肉 2021-01-13 07:43

I find this excellent code, posted by aemkei as answers to this questions:

  1. How do you dynamically load a javascript file? (Think C’s #include)
  2. Use jav
相关标签:
3条回答
  • 2021-01-13 08:28

    The security model in modern browsers prevents JavaScript from making cross-domain requests. That has holes (see every website exploit since the beginning of the internet), but using them is more than a little shady and it's only a matter of time before they're patched.

    0 讨论(0)
  • 2021-01-13 08:31

    You can use the onload and onreadystatechange event to understand when the <script> tag is loaded.

    var script = new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
    
    script.onload = script.onreadystatechange = function(){
        if (!this.readyState ||
            this.readyState == "loaded" || this.readyState == "complete") {
            //script is loaded
        }
    };
    
    0 讨论(0)
  • 2021-01-13 08:33

    What Rex said is correct, although HTML5 has added cross domain messaging and xhr, which require a little bit of work on your part but should be usable to achieve this. Alas they're not yet present in all released browsers (i think the latest betas of safari, firefox, and IE have support for some of these features, but i'm not sure which browsers support which apis)

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