In another question, StackOverflow suggested that it's impossible to guarantee the order in which a browser will process <script>
tags, regardless of their position in the <head>
or <body>
(see comments):
Scripts loading out of order in Chrome
The top answer recommends using a pure-javascript "DOM-loaded" to guarantee that all dependencies are loaded, then running page-specific code.
This made me wonder whether it's safe to use jQuery's recommended $ function as a substitute for the pure-JS DOM-loaded:
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
});
Src: http://learn.jquery.com/using-jquery-core/document-ready/
How can I guarantee jQuery's $ will be defined?
EDIT: Examples of hypothetical failure were requested. Here's one with the external <script>
in <body>
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example 1</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function(){
alert("Loaded.");
});
</script>
</body>
</html>
And one with the external <script>
in <head>
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<script>
$(function(){
alert("Loaded.");
});
</script>
</body>
</html>
Based on Scripts loading out of order in Chrome, either of these may fail.