0

<script> in body or head ?

I have places script tag(of jQuery) in head and when I am trying to place my own script tag in head it is not working. But if I place my own script tag in body it works. MY JS : var h= $('h1') h.click(function(){ console.log("Hello") })

15th Sep 2019, 7:59 PM
harshit
harshit - avatar
2 Respuestas
+ 1
If you place it in the head, the script will load before the document does, so $("h1") will just be null (hard to work with). If you insert it in the body, it will load when the document has loaded, so it works most times. If you want to avoid problems, place everything that runs with the selected element inside this function: $(document).ready(() => { $("h1").on("click", () => { console.log("Hello"); }); });
15th Sep 2019, 8:04 PM
Airree
Airree - avatar
+ 2
If you place any script tag in the head, it will load before the HTML loads but in jQuery, a ready Function is defined $(document).ready(() =>{ // Anything you want to do goes in here }) But if it's JavaScript you can use window.onload = function (){ // Anything you want to do goes in here }; But It's best not to rely on jQuery. Complete JavaScript and know it very well that's the best. http://youmightnotneedjquery.com So learn JavaScript very well. It's just my opinions
16th Sep 2019, 4:32 AM
Qudusayo
Qudusayo - avatar