Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to first load/render HTML/CSS and then Javascript (only if it's necessary)?

How to first load/render HTML/CSS and then Javascript? on a page of website/web-app?

So page loading should not seems slow because of javascript. I read about defer and async but not much clear on this topic. Is to keep javascript at bottom enough?

I want to load html/css first because the javascript i added is for further interactions.

For example I have a buttton which do something using javascript. I want to related javascript file only if user click/press that button otherwise not.

I don't want to preload the JavaScript because it's not necessary it will be used or not until it's required

like image 437
Jitendra Vyas Avatar asked Mar 03 '26 09:03

Jitendra Vyas


2 Answers

Depends on what you are talking about. If you are talking about javascript in the page itself put it at the bottom of the page. If you are referring to loading external libraries you can do so dynamically with javascript.

<script type="text/javascript">
   var hed = document.getElementsByTagName('HEAD').item(0);
    var scrpt = document.createElement("script");

    scrpt.type = "text/javascript";
    scrpt.src = "scriptsource.js";

    hed.appendChild(scrpt);
</script>

More info on this can be found here: http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html

EDIT

You could place your JS inside of the onload event Javascript that executes after page load

like image 94
jon3laze Avatar answered Mar 05 '26 21:03

jon3laze


you can also use this Jquery code to make the HTML on your page load first. This will make sure that the HTML is in place for the javascript to load on it.

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

like image 23
Andrew Zoka Avatar answered Mar 05 '26 22:03

Andrew Zoka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!