Adding Jquery may seems like trival but for someone not from web platform, I really did Felt the fatigue, hunting solution for hours and hours. It was like walking an unknown territory in complete dark, sometimes there were faint light shown by stackoverflow, github and google. But there were also pitch dark times when I, alone, went deep inside the forest of my inexperiences. But finally, once I got that final missing link, It turned out to be quite simple. And ultimately became trivial for me too.
cd assets
and do yarn add jquery
open webpack.config.js
and add the following.
const webpack = require(‘webpack’);
and in the same file inside plugins: [ ]
array, add the following
...
new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery"})
...
open app.js
and add following
import $ from "jquery"global.$ = global.jQuery = $;
It should be working (as told by stackoverlow and google.). we can test it by giving “login-menu” class to button or any html element.
$(".login-menu").click(function (e) {console.log("it works! ")})
But I had this console error like and It kept me going round and round so many times and many hours. This error became the sole reason of my fatigue.
I continued searching where I could go wrong. Stackoverflow, GitHub, and google had ability to show what I had already done, Maybe with some variation but still I felt like I was going round and round. I do not even remember How I went to look the script tag that Included app.js file. It was in the head element of our html.
I hadsomething like this in app.html.eex
<head>
...
<script defer type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
...
And Scripts with defer
always execute when the DOM is ready. Hence when our script with $(“.login-menu”).click(function (e)
did not get the $
variable as it was imported in /js/app.js
which is now defered.
first I test It by removing defer. And It worked like a charm.
<script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
But I learned that without defer, this app.js would compile first, blocking our webpage to load. In my case It is not a problem but I learned that some webapps may have js file larger than the html file. So blocking our web page content to compile this file would make our site load slower.
So I also tried async defer.async does not block the dom and it get’s the js compiled and ready in different thread. And this did too work in my case. But warning , Doing this, it might not run in safari. For me it did not so I simply removed both async and defer.
<script async defer type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
Sometimes not knowing or not getting the big picture is the biggest challange. I am thankful that I went to see this line other wise I would still be going round and round…