2010-10-24 31 views

回答

2

阅读您的评论后,我认为你应该做点别的:

  1. 创建空的元素,其中,广告应该出现(#ad1_empty#ad2_empty,...)在底部
  2. 将广告代码放置隐藏页面(#ad1_full#ad2_full ...)
  3. 当文档准备好,用以假乱真全部替换为空元素

//代码

<div id="ad_empty"><!-- placeholder --></div> 
<div id="ad_content" style="display: none;"> 
    <script src="[ad resource]"></script> 
    <script>inline ad script</script> 
</div> 

<script> 
function replace(oldel, newel, show) { 
    if (typeof newel == "string") 
    newel = document.getElementById(newel); 
    if (typeof oldel == "string") 
    oldel = document.getElementById(oldel); 
    if (newel && oldel) 
    oldel.parentNode.replaceChild(newel, oldel); 
    if (show) 
    newel.style.display = ""; 
} 

window.onload = function() { 
    replace("ad_empty", "ad_content", true); 
    replace("ad_empty2", "ad_content2", true); 
}; 
</script> 

这是可以做到的,你本来想要的东西,顺便说一句(但它也没用)

function foo() { 

    var scripts = document.getElementsByTagName("script"); 
    var parent = scripts[scripts.length-1].parentNode; 
    var tag = parent.nodeName.toUpperCase(); 

    if (tag == "DIV") { 
    alert("called from a <div>"); 
    } else if (tag == "SPAN") { 
    alert("called from a <span>"); 
    } 
} 
+0

这是一个好主意,我可能会这样做。虽然我不能相信第二个作品。它有多糟糕?你知道它是否适用于IE6吗? – CheapSteaks 2010-10-24 17:40:26

+0

http://jsbin.com/igibu4/它与您提供的输入一起工作,但我不会将它用于任何严重的事情。第一种解决方案被广泛用于提高页面加载时间。 – galambalazs 2010-10-24 17:53:22

0

不,这是不可能的。您将不得不手动传递某种参数以确定它从何处被调用。

0

有没有办法做到这一点,脚本可以调用很多不同的方式,只是没有足够的需要这样把它放在spec中的任何方式。

我会想象有一个整体的很多简单的方式做你想实现什么,嵌入<script>各个元素内,立足什么断<script>元素的位置不”似乎是一个合理方法。

那么......你想在这里最终完成什么?

+0

其实,这是可能的。 – SLaks 2010-10-24 16:58:47

+0

@SLaks - 它不是,因为当前元素还没有关闭,所以你不能确定你在哪里(取决于浏览器),例如'setTimeout(foo,0);'会返回...什么? – 2010-10-24 17:00:13

+0

目前使用的广告管理器(百度的广告管理器)需要一个内嵌脚本,用于放置广告。脚本调用'document.write'将广告放置在页面上。从海外访问时,他们的服务器速度很慢,正在减慢页面速度。我希望能够在加载完所有内容后将所有内容移动到页面的底部,但我无法弄清楚如何将脚本的document.write内容放入内联脚本的调用位置。 – CheapSteaks 2010-10-24 17:06:09

3

您可以在DOM中获取当前的最后一个元素

内嵌<script>块中的代码在浏览器分析页面时执行。因此, 最后一个DOM元素将会在脚本之前。

+0

神圣的废话我不能相信这个作品。它会在IE6中工作吗? – CheapSteaks 2010-10-24 17:32:35

+0

@CheapSteaks:我几乎可以肯定;尝试一下。 – SLaks 2010-10-24 18:28:51