为什么我需要使用document.write而不是DOM操作方法? [英] Why do I need to use document.write instead of DOM manipulation methods?

查看:84
本文介绍了为什么我需要使用document.write而不是DOM操作方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一项新的广告服务,据我所知,他们没有提供加载广告的功能界面。我们希望根据用户的屏幕尺寸显示不同的广告尺寸,并且此服务要求您为每种尺寸加载不同的 .js URL。

I'm trying a new ad service, and as far as I know they don't provide a functional interface to loading their ads. We want to display different ad sizes depending on the user's screen size, and this service requires you to load a different .js URL for each size.

我最初尝试编写:

<script type="text/javascript"><!--
    var dochead = document.getElementsByTagName('head')[0];
    var newscript = document.createElement('script');
    newscript.type = "text/javascript";
    newscript.src = '//ads-by.madadsmedia.com/tags/22430/9194/async/' + (screen.width >= 1360 ? '160' : '120') + 'x600.js';
    dochead.appendChild(newscript);
    //-->
</script>

但是我只有一个空白页。我查看了Chrome开发人员工具,它似乎可以正确加载其脚本。他们的脚本从Google加载了其他脚本,它们也出现在DOM中。但是没有广告图像。

but I just got a blank page. I looked in Chrome developer tools and it seemed to be loading their script properly. Their script loads other scripts from Google, and they showed up in the DOM as well. But there was no ad image.

当我将脚本更改为:

<script language="JavaScript" type="text/javascript">
var prot = document.location.protocol;
var adwidth = (screen.width >= 1360 ? '160' : '120');
document.write('<script language="JavaScript" type="text/javascript"'); document.write('src="'+prot+'//ads-by.madadsmedia.com/tags/22430/9194/async/'+adwidth+'x600.js">'); document.write('<\/scr' + 'ipt>');
</script>

它正常工作。我通常不喜欢使用 document.write ,我想知道为什么在这种情况下需要它吗?广告服务的脚本大量使用 document.write ,这是为什么?

it worked properly. I don't generally like using document.write, I wonder why it's needed in this case? The ad service's script makes extensive use of document.write, is that why?

推荐答案

因为他们正在使用 document.write()

< a href = http://ads-by.madadsmedia.com/tags/22430/9194/async/160x600.js rel = nofollow> http://ads-by.madadsmedia.com/tags/22430/ 9194 / async / 160x600.js :

if (!window.ActiveXObject){
  document.write("<div style=\"text-align: center; margin: 0px auto; width:160px; height:600px; position:relative;\">");
// etc.

如果 document.write()不在行内运行并主动打开文档,它将破坏那里的内容。因此,在加载后运行他们的脚本会用他们的内容覆盖您的内容。

If document.write() isn't run in-line on and actively "open" document, it'll clobber what's there. So, running their script post-load overwrites your content with theirs.

这篇关于为什么我需要使用document.write而不是DOM操作方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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