[英]Insert into specific place in head tag without using document.write
This is probably not possible but worth asking. 这可能是不可能的,但值得一提。 I am dynamically inserting script tags into my
head
section of my page. 我正在将脚本标签动态插入页面的
head
。 At the moment I am using document.write
which many of you will frown upon, but it does do the job fine. 目前,我正在使用
document.write
,其中许多人会不满意,但是确实可以完成工作。
However, for the reasons outlined here , I would like to find an alternative to document.write
. 但是,出于此处概述的原因,我想找到
document.write
的替代方法。
Therefore, I need a function that will do this: 因此,我需要一个可以执行此操作的函数:
<!-- 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>
Can anybody suggest anything with jQuery or plain javascript that will insert an element on the page, but also meets these requirements: 任何人都可以使用jQuery或纯JavaScript提出任何建议,这些建议将在页面上插入元素,但也满足以下要求:
Google do this with their Google.load()
method, do they use document.write? Google使用其
Google.load()
方法执行此操作,是否使用document.write? Surely not... 当然不是...
You can look at this article - http://www.phpied.com/non-onload-blocking-async-js/ Similar script is used by facebook for loading their SDK asynchronously. 您可以查看这篇文章-http: //www.phpied.com/non-onload-blocking-async-js/类似的脚本也被Facebook使用,用于异步加载其SDK。
It's cross-browser and can load scripts asynchronously even when the html on the page is not valid (even if the head/body tag are missing). 它是跨浏览器的,即使页面上的html无效(即使缺少head / body标签),也可以异步加载脚本。
Here is an example directly from the facebook's SDK: 这是直接来自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));
You have to make some modifications because it allows you to load the script just a single time (because of if (d.getElementById(id)) {return;}
). 您必须进行一些修改,因为它允许您仅一次加载脚本(因为
if (d.getElementById(id)) {return;}
)。
If we look at the script closer we can see a number of benefits: 如果仔细看一下脚本,我们会发现很多好处:
script
tag (because of the script for async loading) so that's why it's getting the first script element script
标签(因为该脚本用于异步加载),因此这就是它获取第一个script元素的原因 src
src
You can do it different ways. 您可以用不同的方法来做。 As mentioned in various answers here Link .
如这里的各种答案所述链接 。 But I use following
但是我使用以下
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.