Lazy loading knockoutjs with bookmarklet failing

I'm attempting to fix a bookmarklet I wrote to track the URL changes in a single page application, specifically recording timesheet while using asana. It uses a script loader to embed jQuery and KnockoutJS libraries before init. I'm unable to find the ko object in global scope after the KnockoutJS library has initialized and cannot figure out why. To test, login to https://app.asana.com, open the Google Chrome developer tools' Console tab and try the following code:

var koScript=document.createElement('script');
koScript.type='text/javascript';
koScript.src='//ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js';
document.getElementsByTagName('head')[0].appendChild(koScript);

The Network tab shows the script downloading. The Elements tab shows the script as the last child of the head element. Yet ko remains undefined.

Answers


The short version is that:

  1. Asana uses an internal module system that uses module.exports and require - the CommonJS standard you may know from node.js.
  2. The knockout.js file checks the environment to determine if it should be setting window.ko or using module.exports or AMD-style define. If it detects CommonJS-style require it sets properties on exports instead of on a global ko object.

Workaround:

You could temporarily "copy" require off first:

_require = require; require = null

And then it should set window.ko as you're expecting!


Need Your Help

asp.net control for displaying data in a grid

asp.net controls grid

I'm attempting to build a page that displays the same set of information of different "items" in a grid or table. It's akin to a shopping page that displays products in for e.g. a 4 by 3 table.

How to create a horizontally-centered DIV which has a minimum width but can stretch out as needed?

css position css-position

I have a site layout with a fixed header, a fixed footer and a central content section; this is a sample HTML: