Reputation: 3847
I have a problem. I am doing all of this new fancy defer
stuff when I load my JavaScript, as recommended by lighthouse while working on PWA.
{% block head_content %}
<script defer src={% static 'js/jquery.min.js' %}></script>
{% endblock %}
If I was just doing this in a Django tempalte, it would not be a problem, I could just move the <script>
content to a .js
file and defer that also:
{% block content %}
<script>
$( jquery thing
let x = 0; // Do jQuery stuff with NO json_data
);
</script>
{% endblock %}
However, I have a Django application that is doing something like:
{% block content %}
<script>
$( jquery thing
{{ json_data|safe }} // Do jQuery stuff with json_data
);
</script>
{% endblock %}
So if I try and move the script to a separate .js
file I get: SyntaxError: expected property name, got {
.
This very popular Q&A seems not to work if you get $ is not defined
due to using defer, as noted by the top comment. Is my only option to put the script above the portion of the code that uses jquery in the body with no defer? If so, this limits the usefulness of Django's template inheritance.
{% block content %}
<script>
<script src={% static 'js/jquery.min.js' %}></script> // Add above each first-use of jQuery (along with every other relevant library)
$( jquery thing
{{ json_data|safe }} // Do jQuery stuff with json_data
);
</script>
{% endblock %}
Upvotes: 1
Views: 739
Reputation: 4519
I haven't been using Django in a while now, but I don't think you can "defer" that script tag inside your template. That said, you could try one of the following:
01: Load your json_data
into a variable that you can access from an external .js
file.
Something like:
var myJsonData = "{{ json_data|safe }}";
.
Check this thread here for more info.
02: Another option is to create an endpoint that will return that json_data
and call it from an external .js
using ajax. Then you can use the data to do whatever you need.
Something like
$.ajax({
url: "my_django_endpoint",
success: function(result){
// Do jQuery stuff;
}
});
Check this thread here for more info.
We used a framework called T3JS that has a neat way of implementing Option 01 using context. (if you wanna take a look under the topic getConfig).
Hope it helps :)
Upvotes: 1