加载外部脚本有条件不起作用,没有错误

时间:2015-10-30 19:11:00

标签: javascript jquery conditional external-script

在我的情况下,我有:

var url = "http://ads.eyeonx.ch/adserverscript/custom.min.js";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
$('.ad').append(script);
console.log('ad loaded');

我收到了控制台消息&#39; ad loaded&#39;,但广告没有显示,当我检查元素时,<script>没有添加到带有类的div元素ad

Firebug没有出现任何错误,任何明显的错误我都不知道为什么这不会起作用?我至少期望脚本标签出现在元素中。

3 个答案:

答案 0 :(得分:1)

我无法发表评论,但尝试按照以下方式进行评论:

$('.ad').html('<script type="text/javascript" src="'+url+'"></script>');

jQuery.html([string])函数定义.ad的内部HTML。

但是你不需要为此创建变量......

答案 1 :(得分:1)

The exact problem to this is still unknown as to why the code wasn't showing up when inspecting the element, but I noticed a browser error in the Firefox console (not Firebug console) that complained about the external script using document.write();. It appears that this conflicts with the ability to add it after the page has loaded.

The solution in my case was to use an iframe. So instead of:

var url = "http://ads.eyeonx.ch/adserverscript/custom.min.js";
$("<script>").attr({"type": "text/javascript", "src": url}).appendTo(".ad");

I removed the .ad div and used this code to add an iframe dynamically:

$("<iframe>").attr({"class": "ad", "src": "/ads/ad.html", "scrolling": "no"}).prependTo('#container');

Which /ads/ad.html just contains the standard <script></script> stuff.

答案 2 :(得分:0)

&#39;广告加载&#39;无论如何都会打印出来。无论脚本是否成功加载到&#39; ad&#39;类元素。您需要打印广告内容

var result = document.getElementsByClassName("ad")[0].innerHTML;

console.log(result);

或者,您可以尝试查看来源&#39;查看页面上加载的内容。正如@KingCodeFish建议的那样,Chrome Developer工具也是一个强大的工具。