RegEdit
RegEdit

Reputation: 2162

Can jquery be deferred without errors?

In the script below, I'm getting an "Uncaught ReferenceError: jQuery is not defined" error as long as the jQuery.js is included with the defer attribute. It makes no difference that the inline script that is calling the jQuery object is also deferred.

I'm trying to defer the script in order to speed page rendering.

Is it possible to defer jQuery without errors like this?

Uncaught ReferenceError: jQuery is not defined

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery defer test</title>
<link rel="stylesheet" href="styles.css" media="screen" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
<body>
    <p>content goes here...</p>
    <script type='text/javascript' src='scripts.jquery.js' defer='defer'></script>
    <script defer='defer'>
    jQuery(document).ready(function(){
        alert('deferred');
        });
    </script>
</body>
</html>

Upvotes: 3

Views: 1520

Answers (2)

Owen Allen
Owen Allen

Reputation: 11958

The defer attribute only affects external scripts. So your inline javascript will always execute before the external jQuery resource.

From http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#attr-script-defer

The defer and async attributes must not be specified if the src attribute is not present.

Unfortunately for most sites, since they need access to jQuery(function() {}) to init after DOM ready it almost forces you to load jQuery in the head. This is one prime reason to serve jQuery from the external Google CDN since there is a chance it is already cached by your user (from another site), and it will likely be much faster delivery time than your own web server.

There are a couple ways to get around this such as registering your own temp jQuery object simply to store your dom ready functions, but it has its drawbacks.

Upvotes: 2

epsilones
epsilones

Reputation: 11609

You can use defer but only for external scripts !

Upvotes: 0

Related Questions