Search code examples
javascriptappendchildcreateelement

How can I shorten this javascript expression? document.createElement


I would like to shorten this js code, you can?

<script>
    var h = document.getElementsByTagName('head')[0],
        s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = 'file.js';
    h.appendChild(s);
</script>

I guess something like this but not work:

<script>
    var h = document.getElementsByTagName('head')[0],
        s = document.createElement('script').type='text/javascript';
    s.src = 'file.js';
    h.appendChild(s);
</script>

Solution

  • As Frédéric already mentioned above, modern browsers always assume the <script> tag to contain JavaScript by default. So you might get away with something like this.

    (s = document.createElement("script")).setAttribute("src", "/path/to/file.js");
    document.head.appendChild(s);
    

    The only limitation of this dirty implementation is that it doesn't support chaining methods, since setAttribute has no return value.