Ever wanted to pass url parameters to your scripts using the <script> tag then retrieve them from your scripts once they are loaded ?
script.js (thrak.script-1.0.1.js, to be more precise) is made for you. It is designed as kinda jQuery extension function, $.script().
HOW TO USE IT ?
There are two contexts you need to consider for using script.js :
- The context of the caller ; this typically is you html page, which contains the <script> tags that will invoke your script(s).
- The context of the callee, ie your script : this is where you need to retrieve the url parameters that were passed by the caller
CONTEXT OF THE CALLER (YOUR HTML PAGE)
In your html page, you first need :
A reference to jQuery, for example :
A reference to script.js :
A reference to your own script(s), for example :
CONTEXT OF THE CALLEE (YOUR SCRIPT)
When your script executes, the $.script() function is available to it. It returns an object that contains data specific to your script, such as url parameters. You are free to use it (or not) but keep in mind the following aspects :
- $.script() returns the data related to the last <script> tag found in the calling document (your html page). This is in fact the <script> tag that invoked your script. Although it could be possible, the $.script() function is not designed to retrieve data from other scripts that may have been included before yours.
- The return value of $.script() is local to the scope of your script. Once you get out of your script's scope, $.script() may reference another <script> tag. This is why it is really important to save the function's return value if you want to use it later.
The following paragraphs give some various "techniques" to save this data.
SAVING DATA THE CLASSICAL WAY
This is the simplest way : just declare a global variable :
// File : save_classical.js
var save_classical_script_data = $. script ( ) ;
The key issue with this approach is that you have to take care of global variable names.
SAVING DATA THE JQUERY WAY
jQuery plugins typically contain the following lambda-function construction, which is an easy way to map the jQuery global object to the well-known $ ; you simply define a closure and call it immediately, supplying the jQuery global object as a parameter :
( function ( $ )
// The "$" variable is now available to your plugin
} ( jQuery ) ) ;
Just do the same way within your script :
// File : save_jquery.js
( function ( $, $script )
// Now, "$" is a synonym of the jQuery object, and $script is available
// throughout your plugin to reference script invocation data
} ( jQuery, $. script ( ) ) ) ;
This section gives a detailed description of the object returned by the $.script() function, which has no parameters.
The example data values all refer to this example script tag :