How do I call a JavaScript function on page load?

后端 未结 8 1346
轮回少年
轮回少年 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 += `<div>My name is ${name}</div>`; 
      },1500*tmp++)
    }; 
    
    loadContent('Senna');
    loadContent('Anna');
    loadContent('John');
    <div id="content"><div>

    0 讨论(0)
  • 2020-11-22 15:55

    If you want the onload method to take parameters, you can do something similar to this:

    window.onload = function() {
      yourFunction(param1, param2);
    };
    

    This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

    0 讨论(0)
提交回复
热议问题