tags:

views:

53

answers:

2

can anyone explain what happens when you use javascript to insert a javascript based widget?

here's my js code:

var para = document.getElementsByTagName("p");
var cg = document.createElement("div");
cg.setAttribute("class", "twt");
cg.innerHTML='<a href="http://twitter.com/share" class="twitter-share-button" 
data-count="vertical" data-via="xah_lee">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"&gt;&lt;/script&gt;';
document.body.insertBefore(cg, para[1]);

it inserts the twitter widget, before the first paragraph. As you can see above, the twitter widget calls for a javascript that shows how many time the page has been tweeted.

doesn't work in Firefox, Chrome, but semi-works in IE8. What should be the expected behavior when this happens? Does the newly inserted js code supposed to execute? If so, how's it differ from if the code is on the page itself?

+1  A: 

innerHTML does not work to insert script tags (because the linked script, in most browsers, will fail to execute). Really, you should insert the script tag once on the server side and insert only the link at the location of each post (that is, if you are adding this to a blog home page that shows multiple posts, each with their own URLs).

If, for some reason, you decide that you must use one snippet of JavaScript to do it all, at least import the tweet button script in a way that will work, for example, the Google Analytics way or the MediaWiki way (look for the importScriptURI function). (Note that I do not know the specifics of the tweet button, so it might not even work.)

idealmachine
all the pages are static html pages, not from server. Long story short, i cant change that.
Xah Lee
Edited my answer to include links to already-written functions to import JavaScript files.
idealmachine
+1  A: 

In order to execute the JS code you insert into a DIV via innerHTML, you need to do something like the following (courtesy of Yuriy Fuksenko at http://www.coderanch.com/t/117983/HTML-JavaScript/Execute-JavaScript-function-present-HTML )

function setAndExecute(divId, innerHTML) {  
    var div = document.getElementById(divId);  
    div.innerHTML = innerHTML;  
    var x = div.getElementsByTagName("script");   
    for (var i=0;i<x.length;i++) {  
        eval(x[i].text);  
    }  
}

A slightly more advanced approach is here: http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/ - look for <script> tags, take their con­tent and create a new ele­ment into the <head>.

DVK