Ned
Ned

Reputation: 1207

Inserting a <script> tag dynamically via jQuery

I'm trying to add a widget to the page in run-time. Based on this post, I wrote the code below. Unfortunately, it doesn't show anything. Can anybody tell me why?

<script type="text/javascript">
    $(document).ready(function () {
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
        // Use any selector
        $(".testWidget").append(s);
    });
</script>

<div class="testWidget">

</div>

If I put the same script as below, it works and shows some information on the page. However, I should insert the script dynamically, not as static.

<div class="testWidget">
<script src="https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7" type="text/javascript" charset="utf-8"></script>
</div>

Upvotes: 0

Views: 140

Answers (2)

Ross Joo
Ross Joo

Reputation: 180

You should be getting this warning in the console, Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. Here's a way around that:

<script type="text/javascript">
  $(document).ready(function () {
      // Save a copy of the document.write method
      var oldWrite = document.write;

      var s = document.createElement("script");
      s.type = "text/javascript";
      s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";

      // After script is loaded, revert document.write to the original
      s.onload = function () {
        document.write = oldWrite;
      };

      var $testWidget = $('.testWidget');

      // Redefine document.write to make the script's call work
      document.write = function (html) {
        $testWidget.html(html);
      };

      $testWidget.append(s);
  });
</script>

Upvotes: 1

Eduardo Ramos
Eduardo Ramos

Reputation: 416

The script tag you include programatically has to be parsed by the browser. Just by inserting the script tag the included code is not parsed by the JavaScript interpreter.

If you explain what you want to finally achieve I am pretty sure that must be a simpler way to do it.

Upvotes: 0

Related Questions