i'm trying to load javascript asynchronous in the head section. After page loading in developer console i have error that "jQuery is not defined". After one or two refreshes scripts load and work perfectly. Without "async" inside script tag also works. Why this happens and is there any way to fix this. Thanks in advance
-
2Well if your script uses jQuery, it has to be loaded before your script is... It is always safer to just put the script at the end of the `` tag and load normaly. – Dellirium Aug 17 '16 at 10:01
3 Answers
As Dellirium said, JQuery needs to be placed before the javascript code that requires it. You could try placing the JQuery in the <head>
and the script you're running at the end of the body tag <body>
.

- 182
- 2
- 15
-
That makes the race condition a bit less severe, but doesn't remove it. It can still fail. – Aurelia Aug 17 '16 at 10:12
You could add a function to be executed when jQuery is loaded.
<script src="jquery.js&callback=start"</script>
In which &callback=start executes the start() function in your actual javascript file, which you can use to wrap your code around.
function start() {
/* your code */
}
The reason jQuery couldn't be found the first times is because your browser caches the jQuery when it is fully loaded. It has to load the entire file the first time you actually visit or force-reload the page.

- 7,914
- 2
- 46
- 57
When you use async
on a script
tag, the script can execute in any order, at any point during the page load, which is why your scripts work only sometimes. You trade away knowing the order of execution for slightly faster page loads. This usually requires that the scripts you load do not depend on each other or an elaborate loading scheme - usually using one callback function that runs without async and invokes your code when dependencies report they're available.
You should consider if async
is really the right option for your setup.

- 1,052
- 6
- 28