Search code examples
javascriptdjangodynamicappendchildstatic-files

In my Django-project how can I dynamically append a script which is located in the static folder to the head-section?


In my Django-project I would like to dynamically append a script-tag to the head-section. The script I want to append is located in static-folder. The problem is that I don't know how to reference the static-folder in javascript, or if that is even pssible.

This is (a part of) my Javascript:

jQuery( window ).on( "load", () => {
    const script = document.createElement("script");
    script.src = "{% static 'js/myScript.js' %}";
    document.head.appendChild(script);
});

myScript.js could look like this:

console.log("This is myScript")

Of course this does not work. In the console I get:

GET http://127.0.0.1:8000/%7B%%20static%20'js/myScript.js'%20%%7D net::ERR_ABORTED 404 (Not Found).

Is there a way to reference the static-folder inside a javascript?


Solution

  • I found the solution by changing:

    script.src = "{% static 'js/myScript.js' %}";
    

    into:

    script.src = "/static/js/myScript.js";
    

    As simple as that!