Last active
December 15, 2015 15:59
-
-
Save lichgo/5286015 to your computer and use it in GitHub Desktop.
As browsers parse and render page code sequentially, the parsing and execution of Javascript (whether inline or external) code might block rendering the page and downloading other resources (e.g. images) if the js code was not properly placed. Creating dynamic script elements, due to its intrinsic asynchronous loading pattern, has been widely re…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Dynamically load js files, taking an array. | |
| function loadJS(fileList) { | |
| var i = 0, | |
| doc = document, | |
| h = doc.getElementsByTagName('head')[0]; | |
| l(i); | |
| function l(i) { | |
| var js = doc.createElement('script'); | |
| js.type = 'text/javascript'; | |
| var re = function() { | |
| i < fileList.length - 1 ? l(i + 1) : console.log('All scripts loaded.'); | |
| } | |
| if (js.readyState) { | |
| js.onreadystatechange = function() { | |
| if (js.readyState == 'loaded' || js.readyState == 'complete') { | |
| js.onreadystatechange = null; | |
| re(); | |
| } | |
| } | |
| } else { | |
| js.onload = re; | |
| } | |
| js.src = fileList[i]; | |
| h.appendChild(js); | |
| } | |
| } | |
| //One line of code is enough to load all files: | |
| loadJS(['a.js', 'b.js', 'c.js']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment