Loading jQuery

We will need to add the AJAX functionality to our image detail template. In order to use jQuery in our templates, we will include it in the base.html template of our project first. Edit the base.html template of the account application and include the following code before the closing </body> HTML tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
{% block domready %}
{% endblock %}
});
</script>

We load the jQuery framework from Google's CDN. You can also download jQuery from https://jquery.com/ and add it to the static directory of your application instead.

We add a <script> tag to include JavaScript code. $(document).ready() is a jQuery function that takes a handler that is executed when the DOM hierarchy has been fully constructed. DOM comes from Document Object Model. The DOM is created by the browser when a web page is loaded, and is constructed as a tree of objects. By including our code inside this function, we will make sure that all HTML elements we are going to interact with are loaded in the DOM. Our code will only be executed once the DOM is ready.

Inside the document-ready handler function, we include a Django template block called domready, in which templates that extend the base template will be able to include specific JavaScript.

Don't get confused with the JavaScript code and Django template tags. Django template language is rendered on the server side outputting the final HTML document and JavaScript is executed on the client side. In some cases, it is useful to generate JavaScript code dynamically using Django.

In the examples in this chapter, we include JavaScript code in Django templates. The preferred way to include JavaScript code is by loading .js files, which are served as static files, especially when they are large scripts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.58.194