Why does it take two clicks on the button to make this jQuery code work? The browser loads this file and onload the script tag is present in the head section. But this code works only after 2 clicks.
function j1() {
$("button").click(function() {
$("p").hide();
});
}
function load1() {
var target = document.getElementsByTagName("head");
var newScript = document.createElement("script");
var url =
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";
newScript.src = url;
target[0].appendChild(newScript);
newScript = document.createElement("script");
url = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";
newScript.src = url;
target[0].insertBefore(newScript, target[0].firstChild);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="load1();">
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button onclick="j1();">Click me</button>
</body>
</html>