Hello Friends, Today I am going to tell you how to use jQuery before it’s get loaded. Actually It’s best practice to include scripts like jQuery at the end of the Body, but because of this, methods of jQuery is inaccessible and gives not defined error. Here I am sharing both code one which gives error another which works fine.
jquery-fail-test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Use jQuery Before It's Get Loaded</title> </head> <body> <a href="#" id="showhide">Click Here to Show Alert</a> <script> //$ is not defined as $ or jquery is tried to access before it get's loaded $("#showhide").click(function(){ alert("You just clicked!"); }); </script> <!-- REQUIRED JS SCRIPTS --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> </body> </html> |
Output
jquery-success-test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Use jQuery Before It's Get Loaded</title> </head> <body> <a href="#" id="showhide">Click Here to Show Alert</a> <script> window.onload = function(){ //this will attach the event after window load or we can say after jquery or $ is loaded $("#showhide").click(function(){ alert("You just clicked!"); }); }; </script> <!-- REQUIRED JS SCRIPTS --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> </body> </html> |
Output
Download
jQuery Use Before Load Test
1 file(s) 1.41 KB
Thanks
Please do share if you like it
Comments