4

I'm injecting a script like so:

var script = $('<script>', {
    type: 'text/javascript',
    async: true,
    src: 'https://script.js'
});

$('script:first').before(script);

This generates markup like:

<script type="text/javascript" async="async" src="https://script.js"></script>

I would prefer the following syntax:

<script type="text/javascript" async src="https://script.js"></script>

Is this supported when passing options to a jQuery DOM element creator? Or, should I just use plain JavaScript to achieve this?

Huangism
  • 15,324
  • 5
  • 45
  • 64
Sean Anderson
  • 24,467
  • 26
  • 112
  • 219
  • 2
    Why do you want the other syntax? The easiest workaround is probably making the whole thing a string instead of an object that jquery converts. – orhanhenrik Oct 06 '14 at 19:17
  • Partially just curious, but also all other scripts on my page are loaded with requireJS which styles the script using the alternative syntax. It was hard for me to quickly skim all my scripts when one was different. – Sean Anderson Oct 06 '14 at 19:18
  • Looks like this should work: http://stackoverflow.com/questions/13159180/set-attribute-without-value – orhanhenrik Oct 06 '14 at 19:19
  • 1
    It doesn't generate markup at all. It adds a script element to the DOM. – Quentin Oct 06 '14 at 19:24

1 Answers1

18

You can set the attribute using plain JS. Doing it through jQuery will auto-populate the value.

var script = $('<script>', {
    type: 'text/javascript',
    src: 'https://script.js'
});

script[0].setAttribute("async", "");

$('script:first').before(script);
helllomatt
  • 1,299
  • 8
  • 14