4

I wonder why this code works and shows up in the source and the other code does not?

Code showing up:

function test() {
    var scriptElement2 = document.createElement("script");
    scriptElement2.id = 'test';
    var head = document.getElementsByTagName("head")[0] || document.documentElement;
    head.appendChild(scriptElement2);
}

test();

Code not showing up:

function test() {
    var scriptElement2 = document.createElement("script");
    scriptElement2.id = 'test';
    scriptElement2.src = 'http://test.com/ja.js';
    scriptElement2.type = "application/javascript"; 
    var head = document.getElementsByTagName("head")[0] || document.documentElement;
    head.appendChild(scriptElement2);
}

test();

I only added the two lines :

scriptElement2.src = 'http://test.com/ja.js';
scriptElement2.type = "application/javascript"; 

Now the code does not work anymore, the does not show up in the HTML sourcecode. And yes I tried it with an valid src.

iJade
  • 23,144
  • 56
  • 154
  • 243
r-d-r-b-3
  • 325
  • 2
  • 11

1 Answers1

0

Try setting type to text/javascript or leaving it out altogether.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • That worked. But I wonder why ? I always thought it was a good case to set the element type. In previous code I even had to ! – r-d-r-b-3 Aug 17 '13 at 19:47
  • `application/javascript` is the current official MIME type for JS, `text/javascript` is obsolete yet you should use the latter: http://stackoverflow.com/a/876805/358906 - I really want to know why... too. – Nabil Kadimi Aug 17 '13 at 19:49
  • Yes I know that but both of them dont work at all, only with completely leaving them out. – r-d-r-b-3 Aug 17 '13 at 19:51