Adding a <script> to a <div> at Runtime

I recently encountered a situation where I needed to add a <script> block to an existing <div> element on the page. In my case, the <div> was a TWebHTMLDiv. Normally you can change the contents of such a <div> by just setting its HTML property (in Delphi) or its innerHTML property (in JS). However, this apparently doesn't work when the contents contain a <script>.

The situation arose out of wanting to set up an advertising block on the page. The element that you want to contain the ad needs to have a little JS <script> added, which then retrieves the actual ad and updates the element to show it. But if you want to add this block later, or perhaps add in different blocks, then it has to be done at runtime. So I did this. In this example, the containing TWebHTMLDiv is called divAdProvider. The block of JS used is what is provided by Media.net and is paired with another block that is added to the Project.html file (no issues with that one though). Something similar can be done with the Google <script> block as well.

    asm
      var adlocation = document.createElement('div');
      var adscript = document.createElement('script');
      var adscriptinline = document.createTextNode(`
          try {
              window._mNHandle.queue.push(function (){
                  window._mNDetails.loadTag("213148746", "300x250", "213148746");
              });
          }
          catch (error) {}
        `);
      adscript.appendChild(adscriptinline);
      adlocation.appendChild(adscript);
      divAdProvider.appendChild(adlocation);
      adlocation.id = "213148746";
    end;

Note that in order to enter JS code that has multi-line text like that (contained within backticks), the TMS WEB Project Settings need to specifically select ECMA Script 6. Just happens to be one of the few differences between JS versions that I regularly encounter. But this makes it a lot easier to add longer scripts or to copy and paste into here rather than having to muck about with string delimiters and line continuation characters. Though if you wanted to build the script contents via code, that's also an option.