I am new in Symfony2 framework and not fully understand how to work with javascripts and how to include theirs in the best way.
What I need: to include jQuery script
There are several ways to include jQuery in a Symfony project. You can:
The Symfony documentation states:
Bower is a dependency management tool for front-end dependencies, like Bootstrap or jQuery.
If Bower isn't already installed, you can install it globally with npm (require node):
npm install -g bower
According to the Symfony documentation:
A bundle should not embed third-party libraries written in JavaScript, CSS or any other language.
So, we store jQuery directly in the web/
directory which is publicly accessible. To tell Bower where to install packages, create a .bowerrc file in your Symfony project root with this content:
{
"directory": "web/assets/vendor/"
}
Execute bower init
in your project root to create bower.json which will define installed packages. Type enter for every question to answer the default value (select 'globals' for the type of modules).
Bower is ready to install jQuery in your project:
bower install --save jquery
Now you can include jQuery in your template:
Currently Bower does not have a "lock" feature like on Composer. That's why you should probably commit the assets downloaded by Bower instead of adding the directory to your .gitignore file. This will probably change in the future: bower/bower#1748.
Even if Composer is a dependency manager for PHP, you can also use it to install jQuery.
To make Composer able to install components like components/jquery, you need first to add the component-installer:
composer require robloach/component-installer
Then modify your composer.json file to include:
"require": {
"components/jquery": "3.1.1"
},
"config": {
"component-dir": "web/assets/vendor"
},
and execute composer install
. This will install jQuery in the web/assets/vendor
directory.
You can then include jQuery in your template:
For example with Google CDN:
About advantages and disadvantages to using a CDN, I suggest you to read this page.
To make sure your scripts (which require jQuery) will work, jQuery has to be loaded first. So, depending on your page loading requirements, you should either:
, or