简体   繁体   中英

jquery executes before html is loaded

How to make the html load before javascript function

 $(document).ready(function() { var x = 10; if(x == 10) { $('h1').text("Its changed !"); alert("Test"); } })
 <h1>Hello</h1>

Here the alert message will popup,

I also tried,

 $(function(){ window.on('load',function(){ //code }) })

but it doesn't work.

做你想做的基本方法是在body标签末尾的html代码末尾添加脚本。

Your second code snippet should only be :

window.onload = function(){
    /*some code*/
}

The problem appears to be that javascript does not wait for .text() to finish before continuing. Alert then fires, which freezes the browser, preventing text() from completing. There are a couple of ways around this. You could avoid calling functions that freeze the browser (like alert()) or set a timeout before calling alert, like so:

setTimeout(function(){alert('Test')},20);

The timeout will allow time for the previous execution to finish before calling the code within the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM