The reason i'm asking this is because i want to write my own javascript framework from scratch. But as my code scales so does my the amount of code to navigate through.
In order to keep a clear overview I thought it'd be wise to split my code into separate files and let the framework load the files by adding the files to the header of my document.
It's not that big yet (<50kb) but considering the fact that it could get bigger; is there a big performance penalty in doing this or is there a better way to do this?
Update @Antony
Bundling and minifying is definitely on my to-do list. I do expect a speed bump in doing so. Still, wouldn't adding files to the header dynamically during the parsing cause the browser to rethink it's parsing and painting process? Is there a penalty here?
function
If you came here looking for a way to load external files via javascript
var loadExternalFile = function (id, filename, filetype, target, callback) {
if (typeof target === "undefined") {
target = "head";
}
if (filetype === "js") { //if filename is an external JavaScript file
var fileref = document.createElement('script');
fileref.type = "text/javascript";
fileref.src = filename;
fileref.id = id;
if (typeof callback === "function") {
fileref.onload = callback;
}
}
else if (filetype === "css") { //if filename is an external CSS file
var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.href = filename;
fileref.id = id;
if (typeof callback === "function") {
fileref.onload = callback;
}
}
if (typeof fileref !== "undefined") {
document.getElementsByTagName(target)[0].appendChild(fileref);
}
};
// Example
loadExternalFile("example_id", "js/examplefile.js", "js", "document.body");
Loading anything using JS hides these resources from browser's preload scanner. Preload scanner runs very early, before any JS is ran at all, before even real DOM is constructed, and schedules resources to be loaded in a way that browser deems to be optimal.
Loading resources with JS might be justified in some situations, e.g.
media can be used on link), and they're large enough that bandwidth savings are more important than latency.<link> in <body> (it's valid HTML now), theres' <link rel=preload as=…>, etc.In older browsers (IE, Android) there are bugs in handling of load events for scripts and CSS, so use an existing loader that has already dealt with the edge cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With