Robert Robert - 4 months ago 16x
jQuery Question

How to get this jQuery function to obey "document.ready"?

How do I get the jQuery function show below to wait until the DOM has loaded before it's read? I thought that specifying "$(document).ready(function..." at the beginning of the function declaration would do the trick but when my page executes, the function doesn't work and I can see the message "Uncaught ReferenceError: $ is not defined" in my browser's developer console.

This is my base template:

# base.html
<!DOCTYPE html>
{% block page_container %} {% endblock %}
<script src=""></script>
<script src="js/bootstrap.min.js"></script>

This Django template extends (is enclosed by) the base template:

# upload_file.html
{% extends base.html %}

(HTML for form ...)
<label class="btn btn-success btn-file">
Select Photo <input type="file" name="photo" style="display: none;">
(more HTML...)

$(document).ready(function() {

$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);

$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {

var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;

if( input.length ) {
} else {
if( log ) alert(log);



Of course, if I move the script tag that calls jQuery up inside the block in my base template, the function executes. However, I'd prefer to keep my jQuery script element at the bottom of my base template as is illustrated in the Bootstrap documentation. Is there a way to get this function to work if jQuery is referenced after the function that calls it in my page?



I credited fyrb with the answer since he answered first and I ended up doing what he proposed, but I appreciated the other answers too. I'm adding links to some good posts on this subject below for the benefit of others who have this question. There are some good performance reasons for putting your jquery call at the end of the page as will be seen in these articles.


Essentially it boils down to the fact that you need to include jQuery before using its methods.

Typically you would have your

<script src=""></script>
<script src="js/bootstrap.min.js"></script>

In the html <head> tag

I'm less familiar with Django, but is there a reason why you wouldn't want jQuery and bootstrap in the document head?

In any case, you need to include those scripts before your code.

Otherwise, you can take a look at this: $(document).ready equivalent without jQuery