动态加载javascript/json然后立即执行
作者:半瓶墨水 链接:http://www.2maomao.com/blog/load-javascript-dynamically/
晚上想写个json接口,类似delicious的那种webapi。
Python讨论组里有人建议替换已经加载的脚本的src属性,或者重新生成一个script然后加载。
但是这种方式为异步加载,也就是浏览器想啥时候加载完咱不知道,想要加载以后立即进行操作的就不能保证了。
Google一下动态加载javascript找到一大堆,看起来用XMLHttpRequest应该可行,试了一下,搞定了:
function change_style(style) {
var oXmlHttp = GetHttpRequest() ;
oXmlHttp.onreadystatechange = function()
{
if ( oXmlHttp.readyState == 4 )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
{
txt = oXmlHttp.responseText;
alert(txt)
var oScript = document.createElement( "script" );
oScript.language = "javascript";
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = true;
oScript.text = source;
document.body.appendChild( oScript );
}
else
{
alert('操作失败:' + oXmlHttp.statusText + '(' + oXmlHttp.status + ')' ) ;
}
}
}
url = 'http://127.0.0.1:8000/static/styles/pyg/' + style + '.js';
oXmlHttp.open('GET', url, true);
oXmlHttp.send(null);
}
var oXmlHttp = GetHttpRequest() ;
oXmlHttp.onreadystatechange = function()
{
if ( oXmlHttp.readyState == 4 )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
{
txt = oXmlHttp.responseText;
alert(txt)
var oScript = document.createElement( "script" );
oScript.language = "javascript";
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = true;
oScript.text = source;
document.body.appendChild( oScript );
}
else
{
alert('操作失败:' + oXmlHttp.statusText + '(' + oXmlHttp.status + ')' ) ;
}
}
}
url = 'http://127.0.0.1:8000/static/styles/pyg/' + style + '.js';
oXmlHttp.open('GET', url, true);
oXmlHttp.send(null);
}
这里有个更简单的方法(未验证),加载后执行一个helper函数,呵呵:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function () {
if (this.readyState == 'complete') helper();
}
script.onload = helper;
script.src = 'helper.js';
head.appendChild(script);
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function () {
if (this.readyState == 'complete') helper();
}
script.onload = helper;
script.src = 'helper.js';
head.appendChild(script);
比这篇新的: DJango:查找被评论次数最多的前十篇文章(order_by count of related objects)
比这篇旧的: 诡异的输出:printf(const char* format [, argument]… );
相关文章:
其他文章:
比这篇旧的: 诡异的输出:printf(const char* format [, argument]… );
相关文章:
其他文章:

(3 人投票, 平均4.33)

