Documentation
Overview
The old ways:
<script src="framework.js"></script>
<script src="plugin.framework.js"></script>
<script src="myplugin.framework.js"></script>
<script src="init.js"></script>
In the above example, all scripts load and execute serially (by default).
The new way (before </head>
):
<script src="Only.min.js" data-only="init.js" asnyc></script>
In init.js
:
$O.js("framework.js").wait()
.js(["plugin.framework.js", "myplugin.framework.js"])
.wait(function(){
// just inline the code to run framework plugins!
});
In the above example, all scripts load in parallel (by default). "framework.js" will execute first, but "plugin.framework.js" and "myplugin.framework.js" will execute in any order as it is not important (first-come, first-served). The inline code will wait for all 3 scripts to execute before it runs.
How to deal with inline scripts
Only.js philosophy is only one: avoid inline scripts. If your init.js
file size is larger than 128kb when
minifed and gizipped then you should use a modular framework such as require.js instead.
To convert <script src="..."></script>
and <script>/* inline code */</script>
tags into
$O API calls, use these two rules:
- For every
<script src="..."></script>
tag you are replacing, you should have a .js(...) call. -
For every
<script>/* inline code */</script>
inline script block with code in it, we need a .wait(function(){ ... }) call to wrap around the code.
Don't forget that the order of execution will determine if .wait()
call will be used to ensure execution order.
If this still is a little confusing, view Only.js examples below.
Special "Feature" Note(s)
Only.js (LABjs) is able to handle non-feature-testable behavior in older legacy browsers through the use of two small but fairly solid browser inference sniffs. This is different from feature-detection (which is always preferable when possible), but with script-loading quirk behavior, there's no way to feature-detect (in those older legacy browsers), so we simply have to fork behavior based on browser family. So, the following two browser inference sniffs are used:
- (global.opera && Object.prototype.toString.call(global.opera) == "[object Opera]"): The Opera inference relies on the fact that Opera declares an "opera" property on the window object, and that it's a special native, whose toString() return value cannot be duplicated by someone just declaring a window.opera property themselves. This gives a reasonably strong inference that we are in fact in the Opera browser.
- ("MozAppearance" in document.documentElement.style): The Mozilla inference relies on "MozAppearance" only appearing in Gecko browsers in the documentElement's style object. This isn't as solid as the Opera inference, but Gecko/FF has had this property for a really long time and there's a good chance they won't remove it, nor would any other browser have any reason to add a property of that name.
Only.js (LABjs) feature-tests for `async=true` (aka "ordered async") on script-inserted script elements. Read more about this feature on the Dynamic Script Execution Order WHATWG Wiki Page and Henri Sivonen's HTML5 Script Execution Changes.
The HTML Spec has officially been updated to include the "async=false" behavior, that Only.js (LABjs) employs a feature-detect for. FF4+, Webkit (March 2011+), IE10p2+, and Chrome 12+ now have this implemented (and Opera is coming soon).
Only.js (LABjs) also feature-tests for "real preloading". This type of preloading doesn't rely on the "cache preloading" hacks, but instead directly preloads the script (once) and then allows the execution of that code on-demand without a second (cached) request. This functionality has been present in IE since version 4, is suggested in the HTML spec (not required), and has been proposed to be officially declared a requirement. Even if it's never actually standardized any further, it's the best method available for IE, so it's worth it. Read more about the proposal to make this a requirement: Script Execution Control.
Only.js API
Methods
- $O.ready()
- $O.setDefaults()
- $O.setOptions()
- $O.test()
- $O.js()
- $O.wait()
- $O.noConflict()
- $O.end()
- $O.sandbox()
[$O] $O.ready(function inlineScript)
This function is used to defer the execution of a function reference (usually an inline anonymous function) until DOMContentLoaded.
This method is not chain-able, and thus must only be called stand-alone like this: $O.ready({...});. It is usually used with
$O.test()
to ensure the test is executed after the DOM has loaded.
Parameters
inlineScript : (required)
Returns
none
void $O.setDefaults(object optionsObject)
Sets one or more options as global defaults to be used by all $O chains on the page. This method is not chain-able, and
thus must only be called stand-alone like this: $O.setDefaults({...}); before any $O chains in init.js
.
Parameters
optionsObject : an object which contains name/value pairs for the options to set:
- alwaysPreserveOrder: a boolean (defaults to false) which controls whether an implicit empty wait() call is assumed after every script loading, which essentially forces all scripts in the chain to execute serially in order (loading in parallel, by default, is not affected by this setting).
-
useLocalXHR: a boolean (defaults to true) which controls whether Only.js will use an XHR Ajax call to "preload"
scripts which are "local" to the current page's domain (note: does *not* take advantage of any cross-domain Ajax techniques).
This "preload" is effective and quite performant for local scripts.
NOTE: This technique is only attempted to be used if it's set to true and in an older Webkit browser, where neither ordered-async or real-preloading were present, and then only on a local same-domain script. Otherwise, this setting is ignored. - allowDuplicates: a boolean (defaults to false) which controls whether or not Only.js will inspect its internal script URL cache to prevent a script URI from being (accidentally, most likely) loaded a second time. By default, Only.js will not make any duplicate requests for the same script URL. Duplicates within the same chain will simply be ignored, and duplicates across other chains will cause those duplicate calls in the other chains to patiently wait until the single resource loading finishes. If you turn "allowDuplicates" on, then no such de-duplication will be done, either within the chain or between multiple chains.
- basePath: a string (defaults to empty "") which specifies a path value to prepend to every script URL. All relative script URL's are already automatically fully qualified to the page's location, so this basePath should really be used to set some other absolute path to override this qualification for otherwise relative "looking" script URL's.
- cacheBust: a boolean (defaults to false) which adds a random number parameter to every script URL to prevent the URL you requested from being cached. In other words, your requested script will be loaded new each time, since it will have a new random number on the URL each time.
- debug: a boolean (defaults to false) which controls if the web console will be used to log the various steps of loading/processing logic for $O chains. This option is only effective if using the source file for Only-debug.js, or the Only-debug.min.js file. Otherwise, this setting will be ignored. As such, it's safe to have this option turned on in both development and production, but not serve the debug build of the file to production unless you need to troubleshoot an issue in production.
- autoPolyfill: a boolean (defaults to false) which controls if the cdn.polyfill.io service will be used to automatically polyfill and fix current user's browser quirks such as: getting the browser to support HTML5 Elements if it doesn't, etc. The polyfill service automatically determines what to polyfill and what not to, without any extra configuration.
NOTE: The autoPolyfill option can only be used in $O.setDefaults({ ... }). It has no effect in $O.setOptions().
Returns
none
[$O] $O.setOptions(object optionsObject)
Sets one or more options only to be in effect for the current $O chain being executed. This method is chainable (in fact, for it to have any effect, it must be part of a chain!), but it must be the first call in the chain (as changing many of the options mid-chain would create race conditions). So, it must be called like this: $O.setOptions({...}).js(...)...;
Parameters
optionsObject : an object which contains name/value pairs for the options to set
Returns
$O : the chained object reference so subsequent calls to test(), js() and wait()
can be made.
[$O] $O.test(selector)
This function is used to test if one or more selectors exists on the current page.
Parameters
varies (a valid selector string or an array of valid selector strings):
- string : must be a valid selector string that is accepted by
document.querySelector()
- array : an array of valid selector strings that are accepted by
document.querySelector()
Returns
$O : the chained object reference so subsequent calls to test(), js() and wait()
can be made.
[$O] $O.js(varies,...)
This method accepts one or more parameters of varying types. Each parameter value is intended to specify a script resource URI to load.
Parameters
varies (can be any number/combination of the following):
- string : a relative or absolute path URI to a local or remote script to load
- object : an object containing one or more of these properties:
- string src : (required) a relative or absolute path URI to a local or remote script to load
- string type : (optional) the MIME type attribute (eg, "text/javascript", "text/vbscript", etc)
- string charset : (optional) the charset attribute (eg, "utf-8", etc)
- object attributes : (optional) any additional attributes to insert on script tag (eg, "gumby-init" : "false")
- array : an array of parameters of any of the allowed types (including array)
function : if a function is found as one of the parameters, that function will be be executed immediately, which must return a value directly. The return value must be one of the other allowable types (string, object, or array). If the function call results in no return value ("undefined") or the value is "falsy" (false, null, etc), it will be interpreted as no script to load.
This feature allows the construction of "conditional chains", where run-time logic is used to decide ultimately what scripts will be loaded by the $O chain. Eg: load
ie-script.js
if browser is IE, else loadany-script.js
for other browsers.See Examples below for usage demonstration.
Returns
$O : the chained object reference so subsequent calls to test(), js() and wait()
can be made.
[$O] $O.wait(function inlineScript[=null])
This function serves two purposes. Firstly, when inserted into a chain, it tells the chain to ensure that all scripts previously listed in the chain should finish executing before allowing the internal 'execution cursor' to proceed to the remaining part of the chain. Essentially, you can specify "blocking" behavior in terms of execution (not loading!) to ensure dependencies execute in the proper order (regardless of how they were loaded).
Secondly, you can specify a function reference (usually an inline anonymous function) that will be executed in order, immediately
following the chain's previous scripts executing, but before subsequent scripts in the chain are executed. This is synonymous with
inline <script>
tags before or after <script src="...">
type tags.
For instance, it can be used to defer the initialization execution of a script you are downloading, like this:
$O.js("script.js").wait(function(){initScript();});
where initScript() is a function that is defined in
"script.js".
Parameters
inlineScript : (optional, defaults to null)
Returns
$O : the chained object reference so subsequent calls to test(), js() and wait()
can be made.
[$O instance] $O.noConflict(none)
noConflict() rolls back the page to the previous version of Only.js (if any) before this copy of Only.js was loaded, and returns the current instance of $O.
Parameters
none
Returns
$O instance : the current $O instance (from before the rollback)
[$O instance] $O.end(none)
end() creates a new chain-able instance of $O. This allows you to get new chain-able instances of Only.js without breaking a chain. It is different from sandbox() that returns a clean instance (does not handle test() chains properly) and might be problematic on long test() chains. Mostly used with $O.test() without breaking the visible chain.
Parameters
none
Returns
$O instance : a new chain-able instance of $O
[$O instance] $O.sandbox(none)
sandbox() creates a new clean instance of $O. This allows you to get new instances of Only.js.
Parameters
none
Returns
$O instance : a new clean instance of $O
Code Examples
Example 1:
$O.js("script1.js")
.js("script2.js")
.js("script3.js")
.wait(function(){ // wait for all scripts to execute first
script1Func();
script2Func();
script3Func();
});
Example 2:
$O.ready(function(){ // execute after DOMContentLoaded
$O.js({
src: "script1.js",
type: "text/javascript",
attributes: { "gumby-init" : "false" }
})
.js("script2.js")
.js("script3.js")
.wait(function(){ // wait for all scripts to execute first
script1Func();
script2Func();
script3Func();
});
});
Example 3:
// test if #scriptsBox selector exists
$O.ready(function(){
$O.test('#scriptsBox')
.js("script1.js", "script2.js", "script3.js")
.wait(function(){ // wait for all scripts to execute first
script1Func();
script2Func();
script3Func();
});
});
Example 4:
// test for #scriptsBox selector, if it exists then the chain is executed
$O.ready(function(){
$O.test('#scriptsBox')
.js(["script1.js", "script2.js"], "script3.js")
.wait(function(){ // wait for all scripts to execute first
script1Func();
script2Func();
script3Func();
}).end() // implicitly break current test() chain
.js("script4.js") // will execute if #scriptsBox selector does not exist
.wait(function(){script4Func();});
});
Example 5:
$O.ready(function(){
$O.test('#scriptsBox, #pluginsBox') // OR-like selector test; execute if any were found
.js("script1.js").wait() // empty wait() simply ensures execution order be preserved for this script
.js("script2.js") // both script2 and script3 depend on script1 being executed before
.js("script3.js").wait() // but are not dependent on each other and can execute in any order
.js("script4.js") // depends on script1, script2 and script3 being loaded before
.wait(function(){script4Func();});
});
Example 6:
$O.ready(function(){
$O.test('#scriptsBox').test('#pluginsBox') // AND-like selector test; execute if both were found
// also equivalent to: $O.test(['#scriptsBox', '#pluginsBox'])
.js("script1.js") // script1, script2, and script3 do not depend on each other,
.js("script2.js") // so execute in any order
.js("script3.js")
.wait(function(){ // can still have executable wait(...) functions if you need to
alert("Scripts 1-3 are loaded!");
})
.js("script4.js") // depends on script1, script2 and script3 being executed before
.wait(function(){script4Func();});
});
Example 7:
$O.setOptions({alwaysPreserveOrder:true}) // tells this chain to implicitly "wait" on
// execution (not loading) between each script
.js("script1.js") // script1, script2, script3, and script4 *DO* depend on each
.js("script2.js") // other, and will execute serially in order after all 4 have have
.js("script3.js") // loaded in parallel
.js("script4.js")
.wait(function(){script4Func();});
Example 8:
$O.js(function(){
// assuming `_is_IE` defined by host page as true in IE and false in other browsers
if (_is_IE) {
return "ie.js"; // only if in IE, this script will be loaded
}
else {
return null; // if not in IE, this script call will effectively be ignored
}
})
.js("script1.js")
.wait();