JavaScript async & defer: run a script asynchronously
As far as I am aware, in the script element, the async attribute allows the script to download asynchronously (similar to images), while the defer causes the script to wait until the end before executing.
Suppose I have two scripts to include:
<script src="library.js"></script>
<script src="process.js"></script>
I would want them both to proceed asynchronously, and I would want process.js to wait until the end to start processing.
Is there a way to get the library.js script to run asynchronously?
Note
I see there appears to be some discrepancy between different online resources as to the actual role of the async attribute.
MDN & WhatWG suggest that it means that the script should execute asynchronously. Other online resources suggest that it should load asynchronously, but still blocks rendering when it is executed.
javascript asynchronous
add a comment |
As far as I am aware, in the script element, the async attribute allows the script to download asynchronously (similar to images), while the defer causes the script to wait until the end before executing.
Suppose I have two scripts to include:
<script src="library.js"></script>
<script src="process.js"></script>
I would want them both to proceed asynchronously, and I would want process.js to wait until the end to start processing.
Is there a way to get the library.js script to run asynchronously?
Note
I see there appears to be some discrepancy between different online resources as to the actual role of the async attribute.
MDN & WhatWG suggest that it means that the script should execute asynchronously. Other online resources suggest that it should load asynchronously, but still blocks rendering when it is executed.
javascript asynchronous
So you wantlibrary.jsto finish running beforeprocess.jsstarts?
– CertainPerformance
Nov 13 '18 at 5:01
@CertainPerformance Good point. Yes, I would expectprocess.jsto have access to the library.
– Manngo
Nov 13 '18 at 5:03
@Phil I had a look at that link, and I normally regard MDN as authoritative. However, other sites I have looked at definitely suggest thatasyncrefers to loading the script.
– Manngo
Nov 13 '18 at 5:07
Agreed, that's why I removed the comment :)
– Phil
Nov 13 '18 at 5:08
@Phil. Pity. I see that the whatwg.org standard also refers to executing the script … this is getting a little confusing.
– Manngo
Nov 13 '18 at 5:10
add a comment |
As far as I am aware, in the script element, the async attribute allows the script to download asynchronously (similar to images), while the defer causes the script to wait until the end before executing.
Suppose I have two scripts to include:
<script src="library.js"></script>
<script src="process.js"></script>
I would want them both to proceed asynchronously, and I would want process.js to wait until the end to start processing.
Is there a way to get the library.js script to run asynchronously?
Note
I see there appears to be some discrepancy between different online resources as to the actual role of the async attribute.
MDN & WhatWG suggest that it means that the script should execute asynchronously. Other online resources suggest that it should load asynchronously, but still blocks rendering when it is executed.
javascript asynchronous
As far as I am aware, in the script element, the async attribute allows the script to download asynchronously (similar to images), while the defer causes the script to wait until the end before executing.
Suppose I have two scripts to include:
<script src="library.js"></script>
<script src="process.js"></script>
I would want them both to proceed asynchronously, and I would want process.js to wait until the end to start processing.
Is there a way to get the library.js script to run asynchronously?
Note
I see there appears to be some discrepancy between different online resources as to the actual role of the async attribute.
MDN & WhatWG suggest that it means that the script should execute asynchronously. Other online resources suggest that it should load asynchronously, but still blocks rendering when it is executed.
javascript asynchronous
javascript asynchronous
edited Nov 13 '18 at 5:14
Manngo
asked Nov 13 '18 at 4:58
ManngoManngo
3,14331841
3,14331841
So you wantlibrary.jsto finish running beforeprocess.jsstarts?
– CertainPerformance
Nov 13 '18 at 5:01
@CertainPerformance Good point. Yes, I would expectprocess.jsto have access to the library.
– Manngo
Nov 13 '18 at 5:03
@Phil I had a look at that link, and I normally regard MDN as authoritative. However, other sites I have looked at definitely suggest thatasyncrefers to loading the script.
– Manngo
Nov 13 '18 at 5:07
Agreed, that's why I removed the comment :)
– Phil
Nov 13 '18 at 5:08
@Phil. Pity. I see that the whatwg.org standard also refers to executing the script … this is getting a little confusing.
– Manngo
Nov 13 '18 at 5:10
add a comment |
So you wantlibrary.jsto finish running beforeprocess.jsstarts?
– CertainPerformance
Nov 13 '18 at 5:01
@CertainPerformance Good point. Yes, I would expectprocess.jsto have access to the library.
– Manngo
Nov 13 '18 at 5:03
@Phil I had a look at that link, and I normally regard MDN as authoritative. However, other sites I have looked at definitely suggest thatasyncrefers to loading the script.
– Manngo
Nov 13 '18 at 5:07
Agreed, that's why I removed the comment :)
– Phil
Nov 13 '18 at 5:08
@Phil. Pity. I see that the whatwg.org standard also refers to executing the script … this is getting a little confusing.
– Manngo
Nov 13 '18 at 5:10
So you want
library.js to finish running before process.js starts?– CertainPerformance
Nov 13 '18 at 5:01
So you want
library.js to finish running before process.js starts?– CertainPerformance
Nov 13 '18 at 5:01
@CertainPerformance Good point. Yes, I would expect
process.js to have access to the library.– Manngo
Nov 13 '18 at 5:03
@CertainPerformance Good point. Yes, I would expect
process.js to have access to the library.– Manngo
Nov 13 '18 at 5:03
@Phil I had a look at that link, and I normally regard MDN as authoritative. However, other sites I have looked at definitely suggest that
async refers to loading the script.– Manngo
Nov 13 '18 at 5:07
@Phil I had a look at that link, and I normally regard MDN as authoritative. However, other sites I have looked at definitely suggest that
async refers to loading the script.– Manngo
Nov 13 '18 at 5:07
Agreed, that's why I removed the comment :)
– Phil
Nov 13 '18 at 5:08
Agreed, that's why I removed the comment :)
– Phil
Nov 13 '18 at 5:08
@Phil. Pity. I see that the whatwg.org standard also refers to executing the script … this is getting a little confusing.
– Manngo
Nov 13 '18 at 5:10
@Phil. Pity. I see that the whatwg.org standard also refers to executing the script … this is getting a little confusing.
– Manngo
Nov 13 '18 at 5:10
add a comment |
2 Answers
2
active
oldest
votes
I found Sequential script loading in JavaScript which might help you:
(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();
1
So the key is that theloadevent is fired by the<script>element when all of the script's synchronous actions are complete, cool
– CertainPerformance
Nov 13 '18 at 6:09
Not really. The question was about theasyncanddeferattributes. MDN states that scripts inserted usingdocument.createElement, as in the sample above, are executed asynchronously by default.
– Manngo
Nov 13 '18 at 6:24
add a comment |
Both defer and async affect when a script is executed, not when a script is downloaded. I think the confusion comes from the fact that some documentation is a bit sloppy with terms, and the term loaded is unclear as to whether it refers to the fetching of the resource, or the execution of it.
To get library.js to run asyncronously without waiting for the document to load, use async attribute, and to get process.js to wait until document has been parsed, use defer:
<script src="library.js" async></script>
<script src="process.js" defer></script>
Note that library.js is not guaranteed to run before process.js, although it probably will.
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears thatasyncloads the script asynchronously, but still executes synchronously.
– Manngo
Nov 14 '18 at 3:33
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53274079%2fjavascript-async-defer-run-a-script-asynchronously%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
I found Sequential script loading in JavaScript which might help you:
(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();
1
So the key is that theloadevent is fired by the<script>element when all of the script's synchronous actions are complete, cool
– CertainPerformance
Nov 13 '18 at 6:09
Not really. The question was about theasyncanddeferattributes. MDN states that scripts inserted usingdocument.createElement, as in the sample above, are executed asynchronously by default.
– Manngo
Nov 13 '18 at 6:24
add a comment |
I found Sequential script loading in JavaScript which might help you:
(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();
1
So the key is that theloadevent is fired by the<script>element when all of the script's synchronous actions are complete, cool
– CertainPerformance
Nov 13 '18 at 6:09
Not really. The question was about theasyncanddeferattributes. MDN states that scripts inserted usingdocument.createElement, as in the sample above, are executed asynchronously by default.
– Manngo
Nov 13 '18 at 6:24
add a comment |
I found Sequential script loading in JavaScript which might help you:
(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();I found Sequential script loading in JavaScript which might help you:
(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();(function()
//three JS files that need to be loaded one after the other
var libs = [
'https://code.jquery.com/jquery-3.1.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
];
var injectLibFromStack = function()
if(libs.length > 0)
//grab the next item on the stack
var nextLib = libs.shift();
var headTag = document.getElementsByTagName('head')[0];
//create a script tag with this library
var scriptTag = document.createElement('script');
scriptTag.src = nextLib;
//when successful, inject the next script
scriptTag.onload = function(e)
console.log("---> loaded: " + e.target.src);
injectLibFromStack();
;
//append the script tag to the <head></head>
headTag.appendChild(scriptTag);
console.log("injecting: " + nextLib);
else return;
//start script injection
injectLibFromStack();
)();edited Nov 13 '18 at 5:58
answered Nov 13 '18 at 5:52
MamunMamun
26.7k71630
26.7k71630
1
So the key is that theloadevent is fired by the<script>element when all of the script's synchronous actions are complete, cool
– CertainPerformance
Nov 13 '18 at 6:09
Not really. The question was about theasyncanddeferattributes. MDN states that scripts inserted usingdocument.createElement, as in the sample above, are executed asynchronously by default.
– Manngo
Nov 13 '18 at 6:24
add a comment |
1
So the key is that theloadevent is fired by the<script>element when all of the script's synchronous actions are complete, cool
– CertainPerformance
Nov 13 '18 at 6:09
Not really. The question was about theasyncanddeferattributes. MDN states that scripts inserted usingdocument.createElement, as in the sample above, are executed asynchronously by default.
– Manngo
Nov 13 '18 at 6:24
1
1
So the key is that the
load event is fired by the <script> element when all of the script's synchronous actions are complete, cool– CertainPerformance
Nov 13 '18 at 6:09
So the key is that the
load event is fired by the <script> element when all of the script's synchronous actions are complete, cool– CertainPerformance
Nov 13 '18 at 6:09
Not really. The question was about the
async and defer attributes. MDN states that scripts inserted using document.createElement, as in the sample above, are executed asynchronously by default.– Manngo
Nov 13 '18 at 6:24
Not really. The question was about the
async and defer attributes. MDN states that scripts inserted using document.createElement, as in the sample above, are executed asynchronously by default.– Manngo
Nov 13 '18 at 6:24
add a comment |
Both defer and async affect when a script is executed, not when a script is downloaded. I think the confusion comes from the fact that some documentation is a bit sloppy with terms, and the term loaded is unclear as to whether it refers to the fetching of the resource, or the execution of it.
To get library.js to run asyncronously without waiting for the document to load, use async attribute, and to get process.js to wait until document has been parsed, use defer:
<script src="library.js" async></script>
<script src="process.js" defer></script>
Note that library.js is not guaranteed to run before process.js, although it probably will.
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears thatasyncloads the script asynchronously, but still executes synchronously.
– Manngo
Nov 14 '18 at 3:33
add a comment |
Both defer and async affect when a script is executed, not when a script is downloaded. I think the confusion comes from the fact that some documentation is a bit sloppy with terms, and the term loaded is unclear as to whether it refers to the fetching of the resource, or the execution of it.
To get library.js to run asyncronously without waiting for the document to load, use async attribute, and to get process.js to wait until document has been parsed, use defer:
<script src="library.js" async></script>
<script src="process.js" defer></script>
Note that library.js is not guaranteed to run before process.js, although it probably will.
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears thatasyncloads the script asynchronously, but still executes synchronously.
– Manngo
Nov 14 '18 at 3:33
add a comment |
Both defer and async affect when a script is executed, not when a script is downloaded. I think the confusion comes from the fact that some documentation is a bit sloppy with terms, and the term loaded is unclear as to whether it refers to the fetching of the resource, or the execution of it.
To get library.js to run asyncronously without waiting for the document to load, use async attribute, and to get process.js to wait until document has been parsed, use defer:
<script src="library.js" async></script>
<script src="process.js" defer></script>
Note that library.js is not guaranteed to run before process.js, although it probably will.
Both defer and async affect when a script is executed, not when a script is downloaded. I think the confusion comes from the fact that some documentation is a bit sloppy with terms, and the term loaded is unclear as to whether it refers to the fetching of the resource, or the execution of it.
To get library.js to run asyncronously without waiting for the document to load, use async attribute, and to get process.js to wait until document has been parsed, use defer:
<script src="library.js" async></script>
<script src="process.js" defer></script>
Note that library.js is not guaranteed to run before process.js, although it probably will.
answered Nov 13 '18 at 5:20
FlimmFlimm
52.2k23136157
52.2k23136157
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears thatasyncloads the script asynchronously, but still executes synchronously.
– Manngo
Nov 14 '18 at 3:33
add a comment |
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears thatasyncloads the script asynchronously, but still executes synchronously.
– Manngo
Nov 14 '18 at 3:33
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears that
async loads the script asynchronously, but still executes synchronously.– Manngo
Nov 14 '18 at 3:33
I have had a look at the WhatWG Specs, and raised an issue regarding the ambiguity. It appears that
async loads the script asynchronously, but still executes synchronously.– Manngo
Nov 14 '18 at 3:33
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53274079%2fjavascript-async-defer-run-a-script-asynchronously%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
So you want
library.jsto finish running beforeprocess.jsstarts?– CertainPerformance
Nov 13 '18 at 5:01
@CertainPerformance Good point. Yes, I would expect
process.jsto have access to the library.– Manngo
Nov 13 '18 at 5:03
@Phil I had a look at that link, and I normally regard MDN as authoritative. However, other sites I have looked at definitely suggest that
asyncrefers to loading the script.– Manngo
Nov 13 '18 at 5:07
Agreed, that's why I removed the comment :)
– Phil
Nov 13 '18 at 5:08
@Phil. Pity. I see that the whatwg.org standard also refers to executing the script … this is getting a little confusing.
– Manngo
Nov 13 '18 at 5:10