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.
The short version is that:
module.exports
and require
- the CommonJS standard you may know from node.js.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!