简体   繁体   English

在Django中使用“ ad hoc” javascript的最佳实践?

[英]Best practice to use 'ad hoc' javascript in django?

I'd like to use a bunch of ad hoc javascript snippets, eg a jQuery slider which is used only in a single form. 我想使用一些临时的javascript代码段,例如仅以一种形式使用的jQuery滑块。 So I would not not be the best practice to insert these scripts into base.html because it would be imposing unnecessary load to users who don't need that script. 因此,将这些脚本插入base.html并不是最佳实践,因为这会给不需要该脚本的用户带来不必要的负担。

Now the question is how best to include these obscure javascripts, so that they are being called only when really needed? 现在的问题是,如何最好地包含这些晦涩的javascript,以便仅在真正需要时才调用它们?

The way I did this in my Django sites was to include an empty ` 我在Django网站中执行此操作的方式是添加一个空的`

 {% block extrascripts %}
 {% endblock %}

in the head tag of base.html, then use that block for any template that needed to include extra JS: 在base.html的head标签中,然后将该块用于需要包含额外JS的任何模板:

 {% block extrascripts %}
 <script type="text/javascript" src="jquery-ultimate-super-plugin.js" />
 <script type="text/javascript">$.ultimateSuperPlugin(...)</script>
 {% endblock %}

Worked like a charm. 像魅力一样工作。 You can even include {{ block.super }} in your block if you have multiple levels of template inheritance. 如果您具有多个级别的模板继承,则甚至可以在block包括{{ block.super }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM