I need, when loading the page, that the user downloads all the JS files for correct work with the site.
Question: 1) How do I know that the page has finished loading?
2) How to find out what files are in cache?
(The answer is for the case of ordinary scripts, not async and not defer; if you do not know what it is, then the scripts are not async and not defer :)
For a number of reasons (such as document.write ), browsers are forced to load and execute scripts immediately after they meet them in html-code. That is, for this <script> guaranteed that all previous scripts are already loaded and executed (possibly with errors, then they are executed):
<!-- Перед этим тегом jQuery ещё нету --> <script src="path/to/jquery.min.js"></script> <!-- Здесь jQuery уже абсолютно точно загружен, присутствует и работает --> <script src="path/to/some_script_uses_jquery.js"></script> As a result, browsers suspend the html output that is after the script until the script loads and runs. That is why all the scripts are recommended to be placed at the end of the page right before </body> : so that the user sees at least some page content while loading the script, and not a white screen.
After the browser reaches </html> and finishes parsing the page, a DOMContentLoaded event is DOMContentLoaded ; at the time of its call, you can be sure that all the scripts (not async and not defer) are already loaded and executed, and all the html-code is parsed and accessible via the DOM (however, pictures and other files are not necessarily available):
<script> document.addEventListener('DOMContentLoaded', function() { console.log("3: " + (window.jQuery !== undefined)); // true - на момент DOMContentLoaded jQuery уже загружен }); console.log("1: " + (window.jQuery !== undefined)); // false - на момент выполнения этого скрипта ещё не загружен </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> console.log("2: " + (window.jQuery !== undefined)); // true - перед выполнением следующего скрипта // браузер выполняет предыдущие, и jQuery уже есть </script> In addition to DOMContentLoaded there is also a load event, which appears when the entire page is loaded, including pictures and other files. But I do not recommend attaching to it, because, firstly, large pictures on a slow Internet can greatly delay the full page load, and second, the user can stop the page loading, and this event will not happen at all. Usually all scripts are bound to DOMContentLoaded ; jQuery itself does the same.
Source: https://ru.stackoverflow.com/questions/565221/
All Articles
jquerylabel - put your code in the function$(function($) {})2) Why do you need this? - tutankhamun