开发者

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

开发者 https://www.devze.com 2023-04-03 17:05 出处:网络
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 th

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 javascr开发者_高级运维ipt 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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消