Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run jQuery before loading page?

Tags:

html

jquery

I have many images on site and some scripts on it. But scripts can run only after loading whole page. How to accelerate this?

like image 366
Nips Avatar asked Nov 30 '22 16:11

Nips


2 Answers

$(document).ready(function() {
   //code here
});

will run a script when the document structure is ready, but before all of the images have loaded.

if you want to run script before the document structure is ready, just put your code anywhere.

like image 144
dqhendricks Avatar answered Dec 09 '22 18:12

dqhendricks


Sometimes if you only use $(document).ready(), there will be a flash of content.

To avoid the flash, you can hide the body with css then show it after the page is loaded.

  1. Add the line below to your CSS:
    html { visibility:hidden; }
    
  2. And these to your JS:
    $(document).ready(function() {
      //your own JS code here
    
      document.getElementsByTagName("html")[0].style.visibility = "visible";
    });
    

Then the page will go from blank to showing all content when the page is loaded, no flash of content, no watching images load etc.

Inspired by this, thanks to the author.

like image 31
Even Wonder Avatar answered Dec 09 '22 17:12

Even Wonder