How do I call a JavaScript function on page load?

后端 未结 8 1538
轮回少年
轮回少年 2020-11-22 15:18

Traditionally, to call a JavaScript function once the page has loaded, you\'d add an onload attribute to the body containing a bit of JavaScript (usually only c

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 15:49

    For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use

    let ignoreFirstChange = 0;
    let observer = (new MutationObserver((m, ob)=>
    {
      if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
    }
    )).observe(content, {childList: true, subtree:true });
    
    
    // TEST: simulate element loading
    let tmp=1;
    function loadContent(name) {  
      setTimeout(()=>{
        console.log(`Element ${name} loaded`)
        content.innerHTML += `
    My name is ${name}
    `; },1500*tmp++) }; loadContent('Senna'); loadContent('Anna'); loadContent('John');

提交回复
热议问题