スキップしてメイン コンテンツに移動

投稿

ラベル(on demand)が付いた投稿を表示しています

Loading Javascript On Demand (When User Click Button etc.)

Recently, everyone must know placing js script tag at the bottom of html or using "async" attribute so that the page can be rendered not blocked by the scripts loading or excecution. In this post, I will exaplain how to load javascript on demand - e.g. event based. The technique is applicable when javascript is loaded only for a event - like after click button. The usecase might be limited and code becomes a bit complicated so I suggest you should only use this technique at the situation: The script doesn't have to be loaded on user' initial page load. The script is loaded only when user do some interaction on the page - like click button, etc. Most user doesn't trigger the event. That is, if most user trigger the event, then you should simply write script tag. Ok, then now I will show you the code and demo. $(function(){ var scriptLoaded = false; $("#load_button").click(function (){ if (!scriptLoaded) { sc