TL;DR Summary
Easiest way to check if jQuery is loaded is by trying to use it.
However if this check is going to be part of some other logic (not just one-off test you do during development), then your entire code will break (throw an error).
So to prevent this you need to wrap it up with try-catch
blocks like this:
try {
$('#mydiv').text('WORKING!!!');
} catch {
document.getElementById('mydiv').innerText = 'BROKEN!!!';
}
And that's it.
More Details
Obviously there could be some exceptions (although very rare) to the above example.
First of all let me provide you with the full code that was used to generate the image on the top:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>CyberBotMachines</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
</head>
<body>
<style>
body {
background-color: royalblue;
padding-top: 300px;
font-size: 100px;
text-align: center;
color: yellow;
}
</style>
<div id="mydiv">TESTING jQuery ...</div>
<script>
try {
$('#mydiv').text('WORKING!');
} catch {
document.getElementById('mydiv').innerText = 'BROKEN!';
}
</script>
<script src="script.js"></script>
</body>
</html>
And that will result in the screen like this:
Regarding the exceptions I mentioned earlier, it is possible that some other library is also using the same handle $
as jQuery.
And that's why we couldn't use simpler solution like this:
if ($) {
alert('working');
} else {
alert('not working');
}
(also this throws an error if $
is not declared so your entire code breaks, or you have to wrap this in try-catch
as well)
But it is far less likely some other library will define variable jQuery
by accident. And another option you have is to use this piece of code below to check if jQuery is loaded. And also this code will not throw an error if jQuery is not loaded.
if (window.jQuery) {
console.log('jQuery is loaded');
} else {
console.log('jQuery is not loaded');
}
And that is all there is to checking whether jQuery is loaded or not.
Until next time,
Will
P.S. check out my Algo-Trading Journey articles
Top comments (0)