How to Make JS Code Execute After the Page has Finished Rendering (Website Optimization)

Hello,

When I’m creating a website, I try to make it load as fast as possible. I have read lots of techniques on how to achieve this, and the one that is effortless and free to make it, is having JS code run after the DOM is ready.

1. Open the file where your JS code resides. For this article, I will have the following code between my <head> tags:

<script type='text/javascript'>
alert("Hello World!");
</script>

2. Before the JS code starts (after <script type=’text/javascript’>), we will add a line that tells the code to execute after the page has finished loading:

$(document).ready(function() {

So our code will look like this:

<script type='text/javascript'>
$(document).ready(function() {
alert("Hello World!");
}
</script>

Now the big question: why would I want the JS code to load at the end and not immediately after the user visits the page? Because if we have lots of JS code, the page won’t render until the JS is executed, so if you load the JS at the end, the user can use the website while the JS code is loading.

Hope that was clear enough. If you have any question, comment or suggestion, please do not hesitate to contact me and I’ll be more than glad to assist you.

Best Regards,

Richi

Owner of Juapo2Services

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , , , , | Posted under Programming/Coding | RSS 2.0

Author Spotlight

Richi González

Richi González

I started programming when I was 12. I'm a Developer and have been working with the Clip-Bucket script since it came out. I'm the Liaison between Arvixe and Clip-Bucket, so anything you need regarding Clip-Bucket or any particular computer-related subject you need, let me know so I can assist you.

Leave a Reply

Your email address will not be published. Required fields are marked *


− 2 = 7

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>