skip to Main Content

When not miniifying the scripts window.onload does work as expected.

But when I do minified my scripts using Uglify-js Folder it does not.

If I write the following and minify it :

window.onload = function() { 
 // My code 
 console.log( "HELLO TO YOU" );
};

It does not work in the browser.

But I f I write the following:

jQuery(document).ready(function() {
   // My code
 console.log( "HELLO TO YOU" );
});

It works fine!

Even just the console.log() alone does not print any thing using window.onload when minified.

Any ideas??

Here is the output:

window.onload = function() {
    let e = document.querySelector("#main-header")
      , t = e.offsetHeight
      , o = document.querySelector("#et-main-area")
      , n = document.querySelector("#wpadminbar");
    o.style.marginTop = t + "px",
    e.style.top = n ? n.offsetHeight + "px" : "0px"
}
,
jQuery(document).ready((function() {
    let e = document.querySelector("#main-header")
      , t = e.offsetHeight
      , o = document.querySelector("#et-main-area")
      , n = document.querySelector("#wpadminbar");
    o.style.marginTop = t + "px",
    e.style.top = n ? n.offsetHeight + "px" : "0px",
    console.log("HELLO")
}

2

Answers


  1. Chosen as BEST ANSWER

    In my case I ended up reformating my code to have the different functionnalities as named functions on their respective files and called the functions form one single call of the window.onload or better addEventlistener( DOMContentLoaded).

    window.onload = function() {
    
     function one();
    
     function two();
    
     // ....
    
    }
    

  2. window.onload = function() {
    ...
    }
    ,
    jQuery(document).ready((function() {
    ...
    

    You have a comma operator between the function expression and the call to jQuery().ready().

    This means the value assigned to the onload property will be the return value of ready() and not the function expression.


    Assuming the comma is generated by Uglify-js, then this is a bug in Uglify-js and you should probably report it there.


    Asides:

    • addEventListener is preferred over on* properties (and won’t be vulnerable to this bug)
    • DOMContentLoaded is probably better suited to your needs than load
    • The defer attribute is probably better suited to your needs than any kind of event though.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search