Reputation: 11
I'm trying to dynamically insert the Tweetmeme button using Javascript. I'm currently using jQuery throughout the site. Here's the script that I'm using. I basically want to cycle through all the blog entries with a class of journal-entry and append the following JavaScript to the end. This Javascript comes straight from tweetmeme.com. This doesn't work for me though and it has something to do with the code between append(). It doesn't like the second set of script tags.
<script type="text/javascript">
$(document).ready(function() {
$('.journal-entry').each(function(index) {
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>');
});
});
</script>
Any help is appreciated. Thanks.
Upvotes: 1
Views: 3265
Reputation: 536715
Don't do this.
Inserting <script>
HTML content into the DOM is unreliable: it works subtly differently in different browsers, and jQuery won't protect you from the differences.
In particularly, writing innerHTML
never causes a <script>
element's content to execute, but subsequently moving the <script>
element from where it is to a new parent (which is part of jQuery's append
process) may cause the script to execute, but not always (it depends on the browser).
In any case, it'll never work, because looking at button.js
, it is calling document.write()
. That function only makes sense to call at initial document parsing time; if you call it from an event afterwards, the call will simply replace the entire page content, destroying your existing page. A script that calls document.write()
can only be run at document load time, from inside the execution path of a <script>
element. You can't include the script in dynamically-created content at all, because it's not designed for it.
(If it makes you feel any better, it's barely designed at all; the button.js script is a badly broken load of old crap, including improper URL-escaping—using escape
instead of the correct encodeURIComponent
—and missing HTML-escaping. You may be better off well away from these total idiots.)
Upvotes: 4
Reputation: 11230
The closing </script>
in the string in your append(...)
call is closing the overall <script>
Try splitting it up into two strings. E.g:
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></'+'script>');
Upvotes: 2