I tried this, and this work but only if the jquery codes are separated as an External JS, this is my HTML file:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-3.6.1.min.js"></script-->
<script>
if(window.jQuery)
{
alert("jQuery is Active");
}
else
{
alert("jQuery not activated before, activate now");
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.1.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = 'testJS.js';
document.getElementsByTagName('head')[0].appendChild(script1);
}
</script>
</head>
<body>
and here is my JS file
$(document).ready(function(){
alert("jQuery test success");
});
but my problem is the jQuery codes are not always in the external JS file, sometimes the jQuery codes are written within the HTML file itself, this is my way to use jQuery without using external JS:
<html>
<head>
<script>
if(window.jQuery)
{
alert("jQuery is Active");
}
else
{
alert("jQuery not activated before, activate now");
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.1.min.js';
script.onreadystatechange = handler;
script.onload = handler;
document.getElementsByTagName('head')[0].appendChild(script);
}
function handler(){
console.log('jquery added :)');
$('p').css('background-color','green');
alert('handler called');
}
</script>
</head>
<body>
<p id="test">my ID test</p>
<p>My TagName test</p>
</body>
</html>
Now another problem arises, the codes above work as long as jQuery codes are written inside the handler()
function, but don't work if it is written outside the handler()
function, so jQuery here doesn't behave like it usually does, as I know the $(document).ready(function(){})
can be written everywhere and can be split into several parts in different places, how to normalize jQuery behavior here?