I am not sure what is the best approach to load all .js files from a folder from within index.html
The number of .js files will change so I cannot define them in the index.html the usual way. I cannot use php or jQuery solutions which would make it easier.
<script>
var count = 1;
function LoadNext()
{
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "page-" + count++ + ".js"); //Increment the counter so we get the next page each time
newScript.onload = LoadNext; //When the script loads call this function again
document.getElementsByTagName("head")[0].appendChild(newScript)
}
LoadNext();
</script>
-
1If you don't have a server language to work with, you won't be able to accomplish this.Joe Enos– Joe Enos2014年08月01日 19:58:47 +00:00Commented Aug 1, 2014 at 19:58
-
you think client side won't work. i.e using javascript?Keith Power– Keith Power2014年08月01日 20:03:05 +00:00Commented Aug 1, 2014 at 20:03
-
You can load JS with clientside JS, but there's no way of knowing the file names. Do you have a standard naming convention at least?Cheruvian– Cheruvian2014年08月01日 20:03:50 +00:00Commented Aug 1, 2014 at 20:03
-
I would rather load *.js The files will be book.js, page-1.js, page-2.js, page-3.js etcKeith Power– Keith Power2014年08月01日 20:07:06 +00:00Commented Aug 1, 2014 at 20:07
1 Answer 1
You can load a new JS file by creating a new <script> tag.
var filename = "JSDir/JSFile.js";
var newScript = document.createElement("script"); ///Create a new <script> element
newScript.setAttribute("type", "text/javascript"); // Set type to JS
newScript.setAttribute("src", filename); //Set src, your file to load
document.getElementsByTagName("head")[0].appendChild(newScript) //Append this script tag to the end of your head element
If you know your JS files are going to be named basename-1.js you can set a callback so that onload you increment to the next fielname basename-2.js 3, 4... and when the final one fails to load it will stop trying to load further.
var count = 1;
function LoadNext()
{
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "basename-" + count++ + ".js"); //Increment the counter so we get the next page each time
newScript.onload = LoadNext; //When the script loads call this function again
document.getElementsByTagName("head")[0].appendChild(newScript)
}
LoadNext(); //Load basename-1.js
^^Not tested, but if that way of checking the file exists fails. You can always use AJAX and check for 404
4 Comments
basename with page and you should be able to load your page JS files..onerror