开发者

How to dynamically add web widget to a page at runtime

I have a page where I want to demo some web widgets. When user clicks a "Add widget" button, I want to dynamically add the widget he/she selects on the same page in a blank DIV. For example, following is the code for an Addthis button. I tried to add this to the DOM using javascript. I tried both innerHTML and document.write() and neither works. The tags end up in the DOM but the javascript code where the src points to never get executed.


<div class="addthis_toolbox addthis_default_style">
<a href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4cac9ad61a93c252" class="addthis_button_compact">Share</a&开发者_开发百科gt;
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4cac9ad61a93c252"></script>

How can I get the dynamically added javascript to execute or if this is not possible? Please help. Thanks.


You could always include the addThis script block and only insert the DIV tag when you need to. That way, the script always runs whether it's used or not.

The problem is that for security reasons (XSS), the browser does not allow you to load scripts that are from external URLs after the page finishes loading. Also, including a script tag does not automatically execute it.


How about this?

function loadScript(url){
   var element1 = document.createElement("script");
   element1.src = url;
   element1.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(element1);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜