I assume that you suggest putting both the JS script and the data it needs into the template (the data is entered into the JS script via string interpolation)
You can see how this can quickly get out of hand. Below I provide the organization levels of the code in an approximate ascending order (the further, the better, in general)
1. Enable JS using a script tag not embedded in HTML
First: putting JS in your own .js file and including it via the <script> easy. So do it. Moreover, modern browsers can download files in parallel, which is why it is a plus for downloading HTML and JS files at the same time.
2. Avoid submitting data to JS using a Django template
Now another problem that I saw was passing data to JS using <script>data = {"info": "something"}</script> before including their JS code.
This is not ideal for many reasons, due to the fact that in a Django template, data is interpolated line by line:
3. Make JS pull data through the Django API (REST)
However, since you said that you were familiar with Django, I would suggest that you create a view that returns the data that JS needs for your client side in JSON format. For instance. what returns {"info": "something"} on /api/info .
There are many ways to achieve this, here is a start (although it may be obsolete)
Then I would have a script.js file that would read the data using a simple HTTP GET call. Many JS libraries can do this for you easily.
Some advantages of this approach
- Your code (part of JS) is not dependent on part of the data (JSON data)
- You can easily view / test what was being fed into your JSON, as it just requested an HTTP GET
- Your HTML / JS part is completely static and therefore cachable, which improves page loading performance.
- Converting Python data to JSON is quite simple (without kung-fu interpolation)
source share