Web Pattern Library

Github Repo

Menu


Global styles

Global components


Template Structure


Bag, Wishlist, & Checkout

Home / Login

Marketing Modules

Product Listing & Detail

Size & Fit Guides

Personalization

My Account / History

Static pages


JavaScript Helpers

Web Pattern Library:

Global Helper Functions

Some helpful global functions for integrating scripts, particularly from outside the global.js file.

whenDefined function

The whenDefined function is defined in the head section of every template, and can be used for executing arbitrary code when an asynchronous dependency is defined, such as jQuery, or any other function. It is useful for running JavaScript that is dependent on a function that may or may not have already loaded. Generally, you can just add JavaScript to the main build and not have to worry about this, but if you need to say, run a script from inside the HTML file that is dependent on jQuery, this function can be handy.

The arguments for whenDefined are all required, and are as follows:

  1. prop should be a string, such as "jQuery"
  2. scope should be an object that is known to be defined already, like window
  3. callback should be a named or anonymous function to execute as soon as the property is defined. The callback will be called in the scope of the specified scope argument, so within the callback, this will refer to that scope.

Here is an example of the whenDefined function in use:


	whenDefined( "jQuery", window, function(){
		// on dom ready, use jQuery to find all elements with a class of .my-element and call the foo() method on them
		$(function(){
			$(".my-element").foo();
		});
	});`