Django / jQuery:处理模板继承和JS文件加载 [英] Django/jQuery: handling template inheritence and JS files loading

查看:1411
本文介绍了Django / jQuery:处理模板继承和JS文件加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,您如何处理事实,您需要等待JS文件在实际使用之前加载?

In Django, how can you handle the fact that you need to wait for that a JS file is loaded before actually using it?

让我们看看这个问题例如:

let's see the problem with this example:

base.html

<!DOCTYPE html>
<html>

<head>...</head>
<body>
    {% include "content.html" %}

    <script src="jquery.js"></script>
    <script src="awesome-script.js"></script>
</body>
</html>

content.html

<script>
    $(document).ready(function(){
        ...
    });
</script>

这在逻辑上失败( $未定义) 。我可以在调用脚本之前加载jQuery,但是我试图避免在我的主要内容之前加载JS文件,以尽可能快地加载网站。

This logically fail ($ is undefined). I could load jQuery before calling the script, but I'm trying to avoid loading JS file before my main content to keep the website loading as fast as possible.

所以,我能做什么?谢谢。

So, what can I do? Thanks.

推荐答案

由于您的脚本使用jQuery,您只需使用 $(document).ready() $(window).load() 功能的jQuery绑定一个函数对事件DOM已经准备好,并且所有的窗口内容都被加载。

Since your script uses jQuery, you can simply use the $(document).ready() and $(window).load() functions of jQuery to bind a function on the event that DOM is ready and all window contents have been loaded, respectively.

如果你不使用jQuery,看看这些相关问题要了解如何用纯JS模拟上述行为:

If you do not use jQuery, take a look at these relative questions to understand how to imitate the above behaviour with pure JS:

  • pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
  • Javascript - How to detect if document has loaded

编辑1 :包含顺序很重要。您必须在执行需要jQuery的任何脚本之前添加jQuery脚本。

EDIT 1: The inclusion order matters. You have to include the jQuery scripts before any scripts that require jQuery are executed.

编辑2 :您可以通过保持脚本与主要内容分开,或者使用第二个模板:

EDIT 2: You can organize your templates better by keeping the scripts separately from the main content, either with a second template:

base.html

<!DOCTYPE html>
<html>

<head>...</head>
<body>
    {% include "content.html" %}
    {% include "js.html" %}
</body>
</html>

js.html

<script src="jquery.js"></script>
<script src="awesome-script.js"></script>
<script>
    $(document).ready(function(){
        ...
    });
</script>

(在这种情况下,您渲染 base.html

或使用(推荐):

base.html

<!DOCTYPE html>
<html>

<head>...</head>
<body>
    {% block content %}{% endblock %}
    {% block scripts %}{% endblock %}
</body>
</html>

content.html

{% extends 'base.html' %}
{% block content %}
    ...
{% endblock %}
{% block scripts %}
    <script src="jquery.js"></script>
    <script src="awesome-script.js"></script>
    <script>
        $(document).ready(function(){
            ...
        });
    </script>
{% endblock %}    

(在这种情况下,您呈现 content.html

这篇关于Django / jQuery:处理模板继承和JS文件加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆