如何避免在部分视图中加载JavaScript文件?

In my Symfony project, I have two JavaScript files which are loaded in home page:

datetimepicker 
autoComplete 

When I load the partial view in the home page the JavaScript files are not accessible from the partial view.

How do I avoid loading the same JavaScript files multiple times?

I load my partial views through Ajax

//From my partial view 

$(selector).datetimepicker({
  //.....
});

$(selector).autocomplete({
  //.....
});

Error: $(...).datetimepicker is not a function
       $(...).autocomplete is not a function

My guess is that in your base twig file (base.html.twig by default), your including your js files before body ending tag

        {% block javascripts %}
            <script src=.... />
        {% endblock %}
    </body>
</html>

If this is the case the behaviour you're getting is normal, you should either:

  • Include your JS files before echoing your body:

{% block body %}{% endblock %}

  • The best option would be tu move your JS code from your partial into a separate JS file that you can include after the dependencies.

well cant you just do something like

$.ajax({
    success: function(data){
        $(selector).datetimepicker({
           //.....
         });

         $(selector).autocomplete({
           //.....
         });
    }
})

i also may help you wrap the js-code in the partial views you load into

$(document).ready(function($) {

});