Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load order in Symfony2 assetic for JS files

I am currently using a bootstrap template that uses a few JS files. To get them to load I placed all the required JS files in the app/Resources/views/base.html.twig file. Here is a snippet of the code:

{% block body %}{% endblock %}
{% block javascripts %}
    {% javascripts '@ABBundle/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

My code in the child twig file located in AB/ABBundle/Resources/views/Home/show.html.twig has the following code:

{% extends '::base.html.twig' %}
{% block body %}
    blah blah blah normal html code blah blah blah
{% endblock %}

The problem is that when I view this page I get several errors such as "ReferenceError: jQuery is not defined" and "ReferenceError: $ is not defined". This is even though the JS files are included (the names of the JS file are changed as expected).

I found out that the error can be fixed with a rather nasty hack by instead of loading all js files with a single line of code {% javascripts '@ABBundle/Resources/public/js/*' %} I know need to include the js files like this:

{% block javascripts %}
    {% javascripts '@ABBundle/Resources/public/js/jquery.js' %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}

    {% javascripts '@ABBundle/Resources/public/js/jquery.prettyPhoto.js' %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

Is there a way I can force Assetic to load certain JS files first while still using the much shorter: {% javascripts '@ABBundle/Resources/public/js/*' %} option?

like image 757
John Crawford Avatar asked Jan 21 '14 10:01

John Crawford


People also ask

Does the order of JavaScript files matter?

Determining What JavaScript Will Run When Designing your web page using JavaScript requires attention to the order in which your code appears and whether you are encapsulating code into functions or objects, all of which impact the order in which the code runs.

How JavaScript files are loaded?

To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes. Append the script element to the body.


1 Answers

You can specify order which files are loaded using different folder structure like this:

{% javascripts '@AcmeFooBundle/Resources/public/js/file1.js' 
               '@AcmeFooBundle/Resources/public/js/file2.js'
               '@AcmeFooBundle/Resources/public/js/folder/*'
%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
like image 126
TroodoN-Mike Avatar answered Sep 29 '22 20:09

TroodoN-Mike