Mots clés : javascriptjqueryhtmljavascript
94
<!-- index.html --> <html> <head> <title>My Page</title> <script src="my-script.js"></script> </head> <body> <div id="user-greeting">Welcome back, user</div> </body> </html>
// my-script.js document.addEventListener("DOMContentLoaded", function() { // this function runs when the DOM is ready, i.e. when the document has been parsed document.getElementById("user-greeting").textContent = "Welcome back, Bart"; });
<script src="path/to/script1.js" async></script> <script src="path/to/script2.js" async></script>
<script src="path/to/script1.js" defer></script> <script src="path/to/script2.js" defer></script>
88
<script src="script.js" async></script> <script src="script.js" defer></script> <script src="script.js" async defer></script>
<script src="jquery.js" async></script> <script>jQuery(something);</script> <!-- * might throw "jQuery is not defined" error * defer will not work either -->
<script src="document.write(something).js" async></script> <!-- * might issue "cannot write into document from an asynchronous script" warning * defer will not work either -->
<script src="jquery.js" async></script> <script src="jQuery(something).js" async></script> <!-- * might throw "jQuery is not defined" error (no guarantee which script runs first) * defer will work in sane browsers -->
<script src="document.getElementById(header).js" async></script> <div id="header"></div> <!-- * might not locate #header (script could fire before parser looks at the next line) * defer will work in sane browsers -->