0

I am trying to insert a script at a particular position in HTML.

The code:

<script type="text/javascript">
  function createElem() {
    var _rf = escape(document.referrer);
    var _lc = escape(window.location);
    var _url = 'http://advertiser.vizury.com/campaign/showad.php?width=470&amp;height=160&amp;publisher_client_id=90&amp;force_adv_id=VIZADV91&amp;loc=' + _lc + '&amp;rfr=' + _rf;
    var _dm = document.getElementById('vplm');
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = _url;

    _dm.parentNode.replaceChild(s, _dm);
  }
</script>

<ul>
  <li>sddfj</li>
  <li>
    <img id="vplm" onload="createElem();" src="http://i.imgur.com/YKABvxr.gif">
  </li>
  <li>aaaa</li>
</ul>

What it is doing is overwriting the whole page and showing just the final content of the injected script.

When I try to create this script tag via appendChild/replaceChild, the script gets created, but it does not execute.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
web-nomad
  • 6,003
  • 3
  • 34
  • 49
  • 1
    appendChild should work. Show your code. – Barmar Feb 27 '14 at 06:33
  • This doesn't do anything special in HTML context (`document.write` is a piece of text) and is a syntax error in Javascript context. Please show your real code. – John Dvorak Feb 27 '14 at 06:33
  • @JanDvorak Updated my question with the code example i am trying. The script i am appending is also using a `document.write`. – web-nomad Feb 27 '14 at 06:38
  • possible duplicate of [Adding – ˈvɔlə Mar 06 '14 at 09:59
  • @WoIIe the question you are referring to has no relation to the problem asked here. The linked question does not say anything about `document.write` issues i asked for. – web-nomad Mar 07 '14 at 10:51
  • @Pushpesh - Of course it is related to the linked question. Just stick to your appendChild-method (as @Barmar already said) and don't use `document.write()`. `document.write()` won't lead you to the solution you are searching for ;) – ˈvɔlə Mar 07 '14 at 12:05
  • @WoIIe please see my script **again**. I am _not_ using `document.write`! The script i am creating is using it. That's the problem i am trying to figure. – web-nomad Mar 07 '14 at 12:08
  • Now I get it. Sorry for my misunderstanding – ˈvɔlə Mar 07 '14 at 12:11
  • possible duplicate of [JavaScript - controlling the insertion point for document.write](http://stackoverflow.com/questions/1536970/javascript-controlling-the-insertion-point-for-document-write) – Paul Sweatte Mar 25 '14 at 18:59
  • Possible duplicate of [Jquery script is not loaded, on appendChild](http://stackoverflow.com/questions/30344109/jquery-script-is-not-loaded-on-appendchild) – Paul Sweatte Sep 26 '16 at 17:05

0 Answers0