开发者

javascript dynamic script creation vs script defer

开发者 https://www.devze.com 2023-03-08 19:23 出处:网络
I was reading up on non blocking ways of loading javascript.I came upon some interesting concepts, especially a new one to me. The script defer attribute.

I was reading up on non blocking ways of loading javascript.I came upon some interesting concepts, especially a new one to me. The script defer attribute.

I know about dynamically creating scripts and inserting them to the 开发者_如何学编程head of the document, which i have a function for.

for example:

 function loadJS(loc){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = loc
 }

I have seen this defer attribute and Im not sure on how to use it and what its main advantages/disadvantages are?

Thanks in advance guys!


I've been looking for similar answers and was about to post a question when I found this stackoverflow question -- and yours.

So here is what I've found out:

  • The script defer approach hints to a browser to wait until the document has finished loading before executing the script. BUT it still loads the script first (assuming that they're located in the HEAD of the document).
  • jQuery has a .getScript() method which can be used to load any number of scripts whenever and wherever needed. You could even apply it to an onClick event on a link for instance!
  • There are also several libraries aimed at dynamic, non-blocking loading such as LABjs, RequireJS or HEADjs.

I guess it's up to you which approach you choose, if you're only on a small project and are already using and/or used to using jQuery then I'd go with that. Otherwise maybe check out one of the libraries.

Just to state again however that as best as I can tell DEFER will not prevent page blocking when loading scripts. But a typical and very simple solution to this is to include all your scripts in the page footer rather than the HEAD.


People please feel free to correct me if I'm wrong on any of the above! -- Thanks

0

精彩评论

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