Menu

Use the Existing Desktop JavaScript

Remove or use the existing JavaScript on your desktop site.

Keep the original JavaScript from the desktop site on your new mobile site when you want to save:

A. How Adaptive.js Keeps Desktop JavaScript

By default, Adaptive.js preserves all of the JavaScript from the original site. Adaptive.js re-includes these scripts in your base template.

In the adaptation/views/base.js file, the postProcess section includes a line that removes all JavaScript from the original page. However, the section saves the desktop site JavaScript in the desktopScripts key.

Examine the following code snippet:

/**
 * Returns the page context with the
 * desktop JavaScript removed.
 *
 * @param {Object} context
 * @return {Object} context.
 */
postProcess: function(context) {
    context.desktopScripts = $('script').remove();

    return context;
}

We need to remove the scripts because some scripts are located inside HTML elements which are not going to be used on the mobile site. As a result, we need to re-include the removed scripts back in our templates.

In the adaptation/templates/base.dust file, notice the reference to the desktopScripts key, which re-includes the desktop JavaScript at the bottom of the page. By moving all scripts to the bottom, we preserve desktop functionality, while optimizing load order.


B. How to Selectively Keep JavaScript

In other instances, include only some of the desktop JavaScript if you want to:

Keep Specially Marked Classes A common approach to selectively keep JavaScript is to only include scripts that have been marked with a special class.

This approach is described in the following sections.

a. Keep only scripts with the .x-keep class

In the adaptation/views/base.js file, change the desktopScripts key to:

context.desktopScripts = $('script.x-keep').remove();

b. Mark the global scripts to keep

In the adaptation/views/base.js file, add a line in the preProcess section to mark the scripts to keep on every page.

For example, if you want to always keep all scripts that are found in the <head> section, add the following line of code to the preProcess section:

$('head script').addClass('x-keep');

c. Mark page-specific scripts to keep

In the view file associated with this page, add a line in the preProcess section to mark the scripts to keep on this page.

For example, if you want to keep the reviews functionality, mark the corresponding JavaScript file with the .x-keep class:

$('script[x-src*="reviews.js"]').addClass('x-keep');
Edit in GitHub