He escrito un código de mensaje de alerta de JavaScript que muestra el mensaje de alerta primero en los códigos 1 y 2 antes del contenido HTML. ¿Qué debo hacer para ejecutar primero el contenido HTML y luego un código javascript?
Código 1
<!DOCTYPE html> <html> <head> <title>Hello, World !</title> </head> <body> <h1>I am learning JavaScript.</h1> <div id="Content"> <p>This is a paragraph tag. Here the content of html.</p> </div> <script src="text.js"></script> </body> </html>Código 2
<!DOCTYPE html> <html> <head> <title>Hello, World !</title> </head> <body> <h1>I am learning JavaScript.</h1> <div id="Content"> <p>This is a paragraph tag. Here the content of html.</p> </div> <script> alert(" This is alert message."); </script> </body> </html>Hay un evento de load , que se activará DESPUÉS de cargar la página. Puedes escuchar el evento:
window.addEventListener('load', function() { console.log('All assets are loaded'); alert ("This is an alert MSG"); })Puedes usar setTimeout() para esto
<html> <head> <title>Hello, World !</title> </head> <body> <h1>I am learning JavaScript.</h1> <div id="Content"> <p>This is a paragraph tag. Here the content of html.</p> </div> <script> setTimeout(()=>{ alert(" This is alert message.") },2000) </script> </body> </html>En su primer código, simplemente coloque el atributo diferido como se muestra a continuación
<script defer src="text.js"></script>Un script que se descargará en paralelo al análisis de la página y se ejecutará después de que la página haya terminado de analizarse.
para más detalles consulte la URL
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script