HTML and CSS Reference
In-Depth Information
Defer
In addition to
async
, you're very likely to see more scripts that are dependent on other scripts. You could be
referencing an external library or another dependency, like page content, that's present before the ad executes. You
can use a new JavaScript attribute called
defer
, which instructs the DOM parser to load scripts in the order they're
interpreted. For example, you may want to load a larger deferred script before loading another script that references
the previous one. Using the
defer
attribute more often, you'll notice fewer errors when dealing with the sequencing of
script files. Listing 3-5 outlines how to use the
defer
attribute.
Listing 3-5.
Using JavaScript's defer Attribute
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script defer src='
http://code.one.js
'
></script>
<script defer src='
http://code.two.js
'
></script>
<script defer src='
http://code.three.js
'
></script>
<script defer src='
http://code.four.js
'
></script>
</head>
<body>
</body>
</html>
Keep in mind neither
async
nor
defer
blocks the DOM parser, resulting in a better experience for users viewing
the page content. It also goes to mention that defer occurs before the DOMContentLoaded event from the browser.
requestAnimationFrame
HTML5 welcomes users with a
requestAnimationFrame
for dealing with JavaScript animation, versus the old way of
using
setTimeout
or
setInterval
. Use of
requestAnimationFrame
explicitly tells the browser what your intentions
are for animation. Traditionally, developers used the code shown in Listing 3-6 for moving something on the page.
Listing 3-6.
JavaScript setInterval
<script>
window.setInterval(function() {
//move and repeat.
console.log('animate');
}, 1000 / 60); // 60fps.
</script>
Now, we can use
requestAnimationFrame
, as shown in Listing 3-7.
Listing 3-7.
Using requestAnimationFrame
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>