简体   繁体   中英

How to make JavaScript to load after page loading - tried all solutions

I have a problem with my site - http://toppages.co.uk ( built with CakePHP framework) I want to load the javascript after page loading is finished ( Google PageSpeed Insights suggestion), so i moved the entire JavaScript to the footer. Then, after making some tests, i found that JavaScript dones't work properly when is placed to the footer - it loads some times,but some times not.

I tried all possible solutions - first with: document.onload = function.. ,then tried: <body onload="script();"> ,after that tried to load javascript asynchronously with "async" function - notging helps. So far i can't find a way to make it work. Do you have an idea what couse the problem and how can i fix it ?

Try

document.addEventListener('DOMContentLoaded', function(){
    // code here
});

Apparently in IE7 there's no good way to tell, but here's a hack, found here

if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
  document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>')
  var contentloadtag=document.getElementById("contentloadtag")
  contentloadtag.onreadystatechange=function(){
    if (this.readyState=="complete")
      // do stuff here
  }
}

I had this issue before and it was that at the time I was loading jQuery from google, for some reason it didn't load from google. I'm not sure if you have the same issue but what you can try is something like this, if can't load from google, then load local.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
if (!window.jQuery) {
    document.write('<script src="/script/jquery.1.11.0.min.js"><\/script>');
}
</script>

The difference between onload and onready is that onload is in charge of a specific element. and onready is working on the entire page. window.onload vs $(document).ready()
in this case I'would recommend to add jQuery to your page and use
$(document).ready(function () {/*code you'd like to execute*/});
just by inserting <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> at the bottom of your body tag.

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