这可能是不可能的,但值得一问。我将动态地将脚本标记插入到页面的head
部分。目前,我正在使用document.write
,你们中的许多人都会对此不屑一顾,但它确实做得很好。
但是,出于概述here的原因,我想找到一种替代document.write
的方法。
因此,我需要一个可以这样做的函数:
<!-- The document.write writes the new script here synchronously so it will block other scripts -->
<script type="text/javascript">
// Code here that uses the code from the dynamically inserted script
</script>
是否有人建议使用jQuery或普通javascript在页面上插入元素,但同时满足以下要求:
谷歌( Google.load()
)用他们的方法来做这件事,他们使用document.write吗?当然不是.
发布于 2012-11-22 04:42:23
您可以查看本文-- facebook使用类似的http://www.phpied.com/non-onload-blocking-async-js/脚本异步加载它们的SDK。
它是跨浏览器的,可以异步加载脚本,即使页面上的html无效(即使head/body标记丢失)。
下面是一个直接来自facebook的SDK的例子:
(function(d, debug){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
您必须做一些修改,因为它允许您只加载脚本一次(因为if (d.getElementById(id)) {return;}
)。
如果我们仔细看一下脚本,我们可以看到一些好处:
script
标记(因为异步加载的脚本),所以这就是为什么它要获得第一个脚本元素src
发布于 2012-11-22 04:42:36
你可以用不同的方式来做。正如在这里的各种答案中提到的,Link。但我用的是
var load_js = function(data, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = data;
head.appendChild(script);
if(callback != undefined)
callback();
}
load_js("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js");
https://stackoverflow.com/questions/13512903
复制相似问题