Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load jquery asynchronously before other scripts

I've added the async attrib to my javascript inclusion HTML.
So now I've:

<script async src="jquery.myscript.js"></script> 

And this works with all JS I load, all except jquery.

If I add async to jQuery <script> tag all others script who depend from jquery don't work.

In that jsfiddle you can see the problem:
JsFiddle

In the example I've used <script> Mycode </script> instead of including an external file.js, but this doesn't change the situation.

I'd like to run jQuery with async attrib and run other few external scripts asynchronously only after jquery is loaded.

It is possible?

like image 383
Fez Vrasta Avatar asked Feb 11 '13 12:02

Fez Vrasta


People also ask

Can you load jQuery async?

The recommended way to load jQuery is with a script tag. You place it on the bottom of your page and make sure every script that depends on it are loaded after. However, what happens when you want to load all your scripts Asynchronously.

How do I load a JavaScript file asynchronously?

write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously.

Should I async or defer jQuery?

For example, if you're using jQuery as well as other scripts that depend on it, you'd use defer on them (jQuery included), making sure to call jQuery before the dependent scripts. A good strategy is to use async when possible, and then defer when async isn't an option.

Are script tags loaded synchronously?

Freshmarketer JS script can be loaded and executed in two ways: Synchronous code: Scripts are loaded and executed sequentially along with the other web page components. Each time a function is called, the program execution waits until the function is returned before executing the next line of code.


1 Answers

I'd like to run jQuery with async attrib and run other few external scripts asynchronously only after jquery is loaded.

What does that mean? It sounds a lot like you want to load jQuery first, then other things when it's done. So you want to load it synchronously. If you still want to use the async way, you could define an onload function to continue loading other things once jQuery is ready. Or you could use defer. Both of these are explained here: https://davidwalsh.name/html5-async

like image 126
John Zwinck Avatar answered Oct 11 '22 07:10

John Zwinck