I tested my page with an optimizer, and it suggests me to use the async
attribute for all CDN sources that I use, like for instance:
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To run any script I use:
(function(){
})();
I also have JavaScript code in inline script
tags that reference such libraries. However, when I add async
as above, I get an error in the following script:
<script>
(function(){
jQuery.foundation();
ReactDOM.render(<App />,document.querySelector('#app'));
})();
</script>
I've tried adding async
to this script
tag as well, but it still doesn't work. I still get an error that the library loaded with the async
attribute doesn't exist.
Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.
Inline JavaScript executes in the order in which it appears in the page. There's no “deferring” it. As a result, if something in there relies on jQuery, it'll simply throw an error to the console log and refuse to execute.
A/B testing scripts can be loaded in two ways: Synchronously, where scripts are loaded sequentially, one after another, starting with the <head> tag. Asynchronously, where some scripts can be loaded simultaneously.
Wrapping your code in:
(function () {
})();
... does not delay its execution. To delay your script until resources have been loaded, wait to the window load
event:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
Here is an example that loads jQuery with a <script async>
element, and shows the jQuery version via the inline script:
window.addEventListener('load', function () {
console.log(jQuery.fn.jquery);
});
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To capture the event when a particular async
script has been loaded, you could listen to its own load
event. For that to work it is probably the easiest if you give an id
to the script
element of your interest, and make sure the inline code comes after it:
jq.addEventListener('load', function () {
console.log(jQuery.fn.jquery);
});
<script id="jq" async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that the async
(and defer
) attributes have no effect on inline scripts:
The
defer
andasync
attributes must not be specified if thesrc
attribute is not present.
They only have an effect on script
elements that have the src
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With