q & dq
Inline JS is handy for selectively calling external modules and passing data from the page:
This approach can't be used with asynchronously loaded modules because the browser could encounter the inline script before the module has loaded.
q & dq is a tiny pattern and library that solves this problem by queuing inline JS until external scripts are ready:
dq can be used with any asynchronous script loading method.
Installation
q & dq is available via NPM:
npm install --save qdq
It's also available on Bower:
bower install --save qdq
You can also copy source directly from src/dq.js
in this repo.
Using q & dq
Add this to your <head>
, in front of any other script tags:
This creates a q
function, which can be used throughout the rest of the page to queue your external JS calls.
q
's first parameter is the name of your function or module method reference as a string. Any arguments after that will be passed directly to the queued method.
For example, if you had a method that you'd normally call like this:
…you would instead queue it like this:
dq
itself – the JS library provided by this repo – should be added to your external JS. Within your external JS, you must process all the queued scripts by calling dq:
;
Use with AMD & RequireJS
dq
is AMD-friendly and defines itself as an anonymous AMD module if AMD support is detected.
To use dq with RequireJS, declare your queue in the <head>
before you load RequireJS:
You can then start queuing up module/method calls inline:
Since AMD modules aren't part of the global scope, you need to pass them in using the modules
option when you call dq:
;
Advanced use
There are a number of options you can set with your dq call:
;