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
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
Share Improve this question edited Sep 9, 2011 at 21:07 Jitendra Vyas asked Sep 9, 2011 at 20:47 Jitendra VyasJitendra Vyas 153k240 gold badges587 silver badges868 bronze badges 4- 4 Say what? What do you mean? Load where? In what context? What are you trying to achieve? – Oded Commented Sep 9, 2011 at 20:48
- 1 Add some detail to your question. – Incognito Commented Sep 9, 2011 at 20:52
- What if you put your stylesheet include right before the end body tag, then put any script files under that. – Dan Commented Sep 9, 2011 at 20:53
- @Oded - Sorry. I added more info now – Jitendra Vyas Commented Sep 9, 2011 at 20:57
3 Answers
Reset to default 4Depends 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/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
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
});
Simply move your <script>
tags to the bottom of your page, just before the closing </body>
tag