As far as I know and from everything that I have read, Asynchronous support in Servlet 3 does NOT serve web resources. It is used for asynchronously handling HttpServlet
Requests
and Responses
so that your AJAX doesn't get hung up waiting for database connection pooling and the like.
How to asynchronously serve JavaScript and CSS
It is import to place all of your <script>
tags/calls at the end of the <body>
, right before the </body>
. This ensure that your HTML gets loaded before any fetching or running of the scripts happen.
The simplest way to serve JavaScript asynchronously is to use HTML5 and add the 'async' attribute. NOTE: this may only be used for linking JavaScript code with the src
attribute, it will not work for JavaScript in the <script>
tag.
<script async src="../js/your-javascript-code.js"></script>
If you can not use HTML5 or the async
attribute is not supported, you can do the following taken from Thinking Async:
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = '//third-party.com/resource.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
How to asynchronously load CSS using jQuery?
Dynamically loading css file using javascript with callback without jQuery
How to load CSS asynchronously without using JavaScript?
In case you are interested, here is working example of how to use the Servlet 3 asynchronous feature, demonstrating it's intended use, running on JBoss.