Dynamically Inserting [removed] tags into HTML on Page Load

前端 未结 2 1671
误落风尘
误落风尘 2021-01-24 20:01

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

相关标签:
2条回答
  • 2021-01-24 20:42

    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.)

    0 讨论(0)
  • 2021-01-24 20:48

    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>');
    
    0 讨论(0)
提交回复
热议问题