0

Suppose I have this HTML Content:

<html>
<head>
<script src="myscript1.js"></script>
<script src="myscript2.js"></script>
<script src="myscript3.js"></script>
<script src="myscript4.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<!--- CONTENT --->
...
.
.
.
.
.
<!--- CONTENT --->
</body>
</html>

Can I do like this:

<html>
<head>
<script src="myscript1.js"></script>
<script src="myscript2.js"></script>
<script src="myscript3.js"></script>
<script src="myscript4.js"></script>
<script src="jquery.js"></script>
<script>
$(function() {
$("script").attr("async","async");
});
</script>
</head>
<body>
<!--- CONTENT --->
...
.
.
.
.
.
<!--- CONTENT --->
</body>
</html>

Is that valid? And would that actually asynchronously load the javascript or not? :)

Thanks for your time...!

.....................................................................................

1
  • Why don't you try it? Commented Mar 31, 2014 at 11:43

3 Answers 3

1

That wouldn't work.

  1. The script element is blocking, so the script to add the asynchronous attribute wouldn't run until all the previous scripts had run, but which time it would be too late.
  2. You've wrapped the script that adds the attribute in a DOM Ready handler, so even if 1 wasn't true, it still wouldn't work.
  3. The attribute is async, not asynchronous

You need to add the (correct) attribute before the script element is added to the DOM.

Sign up to request clarification or add additional context in comments.

Comments

1

It won't work. As you are printing the script tags BEFORE your jquery code, the browser will load those scripts file before running your code.

2 Comments

Okay, say I added that before every script. Would that work then?
No i won't work either, as when you are looking for the script tags with jQuery, the scripts are not printed yet.
0

You can use getScript() to load scripts asynchronously

$.getScript("/path/to/script.js",function(){
  // loaded
}); 

-----> https://api.jquery.com/jQuery.getScript/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.