Please help me by answering with a short theory behind how it works as I would like to understand the logic rather than just get an answer. If you know of any material that explains it for beginners then please reference it. I have spent quite a lot of time researching and have come up blank and find the name or anything that explains this behavior.
My question is and want to understand, I thought the way browsers parse the html is line by line. When it encounters a <script> tag everything else comes to a halt (this basic example) whilst it passes it off to the js interpreter to also complete line by line. Once it has finished it then passes it back to the html parser to continue with the rest of the page
So my question is from the short example below, why is "find" being loaded before backup.js has completed, when I remove backup.js and have jQuery instead the code in console.log(find); works as expected, but when jQuery is removed from html and asked to be added via backup.js, which is still the first tag encountered before the console.log(find); at the bottom, it does not work? I get the following error message:
ReferenceError: $ is not defined
var find = $('.link');
Makes me believe that var find = $('.link'); is being attempted to be accessed before backup.js and jQuery have finished loading, but why is this when "find" comes long after backup.js? Or am I doing something wrong with the Javascript code in backup.js that adds it after rather than earlier?
I have this short piece of html:
<html>
<head>
<!--<script src="https://code.jquery.com/jquery-1.11.1.js"></script>-->
<script type="text/javascript" src="backup.js"></script>
<meta charset="UTF-8">
<title>My Web Page</title>
</head>
<body>
<p>hello</p>
<div class="link">test</div>
<script>
var find = $('.link');
console.log(find);
</script>
</body>
</html>
In backup.js I have this:
if(typeof jQuery=='undefined') {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'https://code.jquery.com/jquery-1.11.1.js';
head.appendChild(script);
console.log('jquery not found');
}
else{
console.log('jquery found');
}