Dynamically loading resources with Sitemagic CMS
Sometimes you want to be able to reduce the initial payload of you website, making it load faster. One way to do this is to load resources when they are needed, not before. For that Sitemagic CMS features SMResourceManager. It allows you to dynamically load (on-the-fly) JavaScript and StyleSheets (CSS).
// Load a single JavaScript file non-blocking
SMResourceManager.LoadScript("extensions/test/test.js", function(src)
{
alert("JavaScript " + src + " loaded and ready to be used!");
});
The example above will load test.js . When it has finished loading, the callback provided is invoked, passing the script path as an argument.
Sometimes we need to load multiple JavaScript files, and to make sure they are loaded in a particular order as they may depend on one another. We use the LoadScripts function to chain load JavaScript files.
// Load multiple JavaScript files
SMResourceManager.LoadScripts(
[
{
source: "extensions/test/menu.js",
loaded: function(cfg) { alert("JavaScript " + cfg.source + " loaded"); }
},
{
source: "http://cdn.domain.com/chat.js",
loaded: function(cfg) { alert("JavaScript " + cfg.source + " loaded"); }
}
],
function(cfgs)
{
alert("All files loaded");
});
In this example we use LoadScripts that takes an array of configuration objects as an argument. Each configuration object defines a source property (path) and optionally a loaded property defining a callback which is invoked when that particular file has been loaded. The loaded callback takes the configuration object as an argument.
Notice how LoadScripts also accepts an optional callback function which is invoked when all files have finished loading. This callback receives the array of configuration objects initially passed to the LoadScripts function.
StyleSheet (CSS) files can be loaded the exact same way which the following examples demonstrate. There is one important difference though. LoadStyleSheets loads all stylesheets in parrallel, rather than chain loading them. This is possible because stylesheets do not depend on each other. Stylesheets files will be applied to the document in the order defined, which is important if one stylesheet define styles that another stylesheet tries to override. So basically the LoadStyleSheets function works much like the browser does when loading styleshets in the <head> section.
// Load a single stylesheet file non-blocking
SMResourceManager.LoadStyleSheet("extensions/test/test.css", function(src)
{
alert("StyleSheet " + src + " loaded!");
});
// Load multiple stylesheets non-blocking in parrallel
SMResourceManager.LoadStyleSheets(
[
{
source: "extensions/test/menu.css",
loaded: function(cfg) { alert("StyleSheet " + cfg.source + " loaded"); }
},
{
source: "http://cdn.domain.com/chat.css",
loaded: function(cfg) { alert("StyleSheet " + cfg.source + " loaded"); }
}
],
function(cfgs)
{
alert("All files loaded");
});