I am making a simple angular 2 application using angular cli tool. In my code I have to include jquery.js file in my index.html. jquery.js is under node_modules directory but the statement
<script src="../node_modules/jquery/dist/jquery.js"></script>
in the index.html seems to be not working:
Failed to load resource: http://localhost:4200/node_modules/jquery/dist/jquery.js the server responded with a status of 404 (Not Found)
How can I make sure that the jquery.js is included in index.html? Thanks for any help.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
You can write your JavaScript files in "modules" and then reference them as dependencies in other scripts. Or you can use RequireJS as a simple "go get this script" solution. require(['some-dependency'], function(dependency) { //Your script goes here //some-dependency. js is fetched. //Then your script is executed });
Add external JS files. If you want include any js library in your angular application like as jquery, bootstrap etc.. You can use npm command for install this library. For example we are installing jquery and bootstrap library: After installing this library add them in styles and scripts array in angular.json respectively css and js.
Another way of including HTML content from other files is to use the <include> directive and the virtual parameter keyword. The virtual parameter keyword is used to denote the file which needs to be embedded. This is known as server-side includes. Angular also provides the facility to include files by using the ng-include directive.
The easiest way to add external dependencies to your Angular projects is through npm. The second best option is to add script tags to the web page that hosts the application. However, that option only works if you have access to the host page. Barring that, you’ll have to load your JavaScript files dynamically.
Here’s one if your index file is at the root. (If you aren’t doing any routing, you don’t need this, but who really does a website with only a single view.) Angular reads all the html tags, and it uses the base tag to figure out where the app is and all the routing won’t work unless you have that.
In order to include a global library, you have to add the jquery.js file in the scripts
array from angular-cli.json:
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
After this, restart ng serve
if it is already started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With