[removed] not working for me?

前端 未结 8 1955
栀梦
栀梦 2021-02-07 14:17

Well I\'m simply playing around with a userscript of GreaseMonkey and here\'s just something simple I attempt to do;

function test() {
document.getElementById(\'         


        
相关标签:
8条回答
  • 2021-02-07 15:05

    It is because you are assigning the result of the test function instead of the function itself due to the parentheses () on the last line.
    Remove them and it may work.

    If not then:

    Apparently that is by design. [Chrome - v57]
    Use document.addEventListener("DOMContentLoaded", <function_name>); instead.

    See: Page lifecycle : DOMContentLoaded

    0 讨论(0)
  • 2021-02-07 15:06

    What you need is:

    window.onload = function () {
    // do the work after everything was loaded (DOM, media elements)
    }
    

    document.onload it doesn't exist. It works if you at least target some specific element from document for example:

    document.querySelector("img").onload = function ()
     {// do your thing after 'img' was loaded}
    

    You have other options if you want to execute some code after the DOM is the only element ready without wait for media elements to load like:

    • Import an async script tag loading the file with the code: You can place this tag wherever you want in DOM and it will not interrupt nothing, will load after the DOM finish to load. you should take a look to MDN documentation about that.

    • If you take a look again in MDN documentation they will recommend you in section Notes to use DOMContentLoaded and DOMFrameContentLoaded events which can be handling by addEventListener. So, if you do this:

    document.addEventListener('DOMContentLoaded', handlerFunc);

    Will work for you.

    I hope this can be helpful for you...

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