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) { scriptLoaded = true; var element = document.createElement("script"); element.onload = function() { // code will be executedafter the javascript loaded $("#script_message").html("script is loaded!"); }; // put your javascript url // note: protocol http or https is mandatory. element.src = "http://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js"; document.body.appendChild(element); } }); });
This is the demo of above code snippet.
script is not loaded
2014/06/01: After I have written this post, I found that this technique is common...
I bought "High Performance JavaScript " and found a lot of performative javscript techniques.
You should definitely buy the book. The book explains how javascript is loaded and how to apply async loading with more details.
コメント