同步动态加载JavaScript [英] Dynamically loading JavaScript synchronously

查看:136
本文介绍了同步动态加载JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模块模式,其中一个我想要做的是动态地包含一个外部JavaScript文件,执行该文件,然后在我的模块的 return {} 中使用文件中的函数/变量。 / p>

我无法弄清楚如何轻松地做到这一点。有没有标准的方法来执行伪同步外部脚本加载?

  function myModule(){
var tag =使用document.createElement( 脚本);
tag.type =text / javascript;
tag.src =http://some/script.js;
document.getElementsByTagName('head')[0] .appendChild(tag);

//应该去这里以确保在执行返回之前加载文件

return {
external:externalVariable
}
}


解决方案

只有一种方法可以同步加载和执行脚本资源,即使用同步XHR



这是如何执行此操作的示例

  //得到某种XMLHttpRequest 
var xhrObj = createXMLHTTPObject();
//打开并发送同步请求
xhrObj.open('GET',script.js,false);
xhrObj.send('');
//将返回的内容添加到新创建的脚本标记
var se = document.createElement('script');
se.type =text / javascript;
se.text = xhrObj.responseText;
document.getElementsByTagName('head')[0] .appendChild(se);

但是你通常不应该使用同步请求,因为这会阻止其他一切。
但话虽如此,有些情况当然是合适的。



我可能会将包含函数重构为异步模式,尽管使用onload处理程序。


I'm using the module pattern, one of the things I want to do is dynamically include an external JavaScript file, execute the file, and then use the functions/variables in the file in the return { } of my module.

I can't figure out how to do this easily. Are there any standard ways of performing a pseudo synchronous external script load?

function myModule() {
    var tag = document.createElement("script");
    tag.type = "text/javascript";
    tag.src = "http://some/script.js";
    document.getElementsByTagName('head')[0].appendChild(tag);

    //something should go here to ensure file is loaded before return is executed

    return {
        external: externalVariable 
    }
}

解决方案

There is only one way to synchronously load and execute a script resource, and that is using a synchronous XHR

This is an example of how to do this

// get some kind of XMLHttpRequest
var xhrObj = createXMLHTTPObject();
// open and send a synchronous request
xhrObj.open('GET', "script.js", false);
xhrObj.send('');
// add the returned content to a newly created script tag
var se = document.createElement('script');
se.type = "text/javascript";
se.text = xhrObj.responseText;
document.getElementsByTagName('head')[0].appendChild(se);

But you shouldn't in general use synchronous requests as this will block everything else. But that being said, there are of course scenarios where this is appropriate.

I would probably refactor the containing function into an asynchronous pattern though using an onload handler.

这篇关于同步动态加载JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆