动态加载iframe源

时间:2012-11-13 20:43:36

标签: google-maps iframe

我的网页上有一些谷歌地图嵌入;这些使我的页面变慢,所以我想在加载页面后加载它们,所以我尝试这样的东西。不幸的是,地图的iframe源会发生变化,但地图内部没有加载,只是空白。

e.g。链接:

<iframe width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.co.in/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Megarugas+Banquet+and+Lawn,+Opp.+Chandivali+studio,&amp;aq=&amp;sll=19.127228,72.865035&amp;sspn=0.013259,0.022724&amp;ie=UTF8&amp;hq=Megarugas+Banquet+and+Lawn,+Opp.+Chandivali+studio,&amp;hnear=&amp;t=m&amp;cid=15174344858031542989&amp;ll=19.115165,72.894802&amp;spn=0.024329,0.025663&amp;z=14&amp;iwloc=A&amp;output=embed"></iframe><br /><small><a href="https://maps.google.co.in/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=Megarugas+Banquet+and+Lawn,+Opp.+Chandivali+studio,&amp;aq=&amp;sll=19.127228,72.865035&amp;sspn=0.013259,0.022724&amp;ie=UTF8&amp;hq=Megarugas+Banquet+and+Lawn,+Opp.+Chandivali+studio,&amp;hnear=&amp;t=m&amp;cid=15174344858031542989&amp;ll=19.115165,72.894802&amp;spn=0.024329,0.025663&amp;z=14&amp;iwloc=A" style="color:#0000FF;text-align:left">View Larger Map</a></small>

HTML:

<iframe id="blabla"></iframe>

JS:

$(window).load(function() {
   if ($('#blabla').length <= 0) { return; }  // to avoid errors in case the element doesn't exist on the page / removed.
   $('#blabla').attr('src','//example.com/page');
});

1 个答案:

答案 0 :(得分:1)

src不会在脚本中解析,您必须用&amp;替换&的所有出现

您无需自行完成此操作。

创建一些元素,将html设置为src,然后检索元素的文本:

$(window).load(function() {
   $('#blabla').attr('src',$('<span/>').html('https://example.com/page').text());
});

附加说明: 您不需要检查$('#blabla')的长度,当jQuery对象为空时,您不会收到错误。