Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create script tag with async attribute

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?

like image 706
Sean Anderson Avatar asked Oct 06 '14 19:10

Sean Anderson


1 Answers

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);
like image 196
helllomatt Avatar answered Sep 30 '22 12:09

helllomatt