Ad

Javascript In A Seperate File Not Working In Django

I am relatively new to python and Django, but have more experience with Javascript/jQuery. I am now working with Django and want to include javascript in my base.html-template. I have included the link to the jQuery cdn. The head-section looks like this:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Interceptie kennisbank</title>

    <link rel="stylesheet" href={% static "css/reset.css" %}>
    <link rel="stylesheet" href={% static "css/style.css" %}>

    <!-- link to jQuery: -->
    <script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous">
    </script>

    <!-- javascript event handlers: -->
    <script type="text/javascript" href={% static "js/events.js" %}></script>
</head>

When go to page source in Chrome I can click the link to /static/js/events.js and the source of that file will be shown.

enter image description here

This proves that the javascript is included correctly, doesn't it? But the load-event is never triggered and nothing is logged to the console. I tried putting the link to the js-file at the bottom of the body, and that too did not work.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Interceptie kennisbank</title>

    <link rel="stylesheet" href={% static "css/reset.css" %}>
    <link rel="stylesheet" href={% static "css/style.css" %}>

    <!-- link to jQuery: -->
    <script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous">
    </script>

    <script>
        jQuery( window ).on( 'load', function(){
            console.log('3. Javascript geladen');
        });
    </script>

    <!-- javascript event handlers: -->
    <script type="text/javascript" href={% static "js/events.js" %}></script>
</head>

When I add the script itself to the base.html is does work though. It works when I put it in the header and it works when I put it in the body.

Of course I prefer to put my javascript in a seperate file. Can anybody shed any light on this issue?

Ad

Answer

<script type="text/javascript" src="{% static 'js/events.js' %}"></script>

correct your code as above and add {% load static %} on top of the file, if it is not there. Similar pattern is applicable for css links also

Ad
source: stackoverflow.com
Ad