analytics.js icon indicating copy to clipboard operation
analytics.js copied to clipboard

analytics.js and r.js optimization issue

Open rowanu opened this issue 13 years ago • 7 comments

I'm trying to use analytics.js with jrburke/r.js, but am having problems. After optimization (which runs fine), I get the following error when launching my application in the browser:

Mismatched anonymous define() module: function (){return require("analytics")}

Has anyone else had this problem? Are there any 'non-standard' steps I should be taking to use analytics.js with r.js?

rowanu avatar Sep 09 '13 18:09 rowanu

Hey @rowanu can you explain how your AMD modules are setup? Are you wrapper analytics.js in AMD? Code example would be really helpful. Not sure what's going on here.

ianstormtaylor avatar Sep 17 '13 01:09 ianstormtaylor

I was just including the build (un-minified) analytics.js file downloaded from the repo's root directory(ie. this file).

In my main.js I have the path to the library and import shim:

require.config({
     paths: {
         'analytics':    'libs/analytics/analytics',
         'backbone':     'libs/backbone/backbone',
         ...
     },
     shim: {
         'analytics':           {exports: 'analytics'},
         'backbone':             {exports: 'Backbone',
         ...

In development (ie. un-compiled) mode it all works fine, so it makes me think the basic analytics.js + reuqirejs is fine. It's just when I go to optimize (using r.js) that the error pops up.

I have used requirejs and r.js before, but might be missing something basic? I don't have any analytics.js-specific configuration in my build file.

rowanu avatar Sep 17 '13 15:09 rowanu

Honestly I have no idea, really sorry. I've never used r.js and haven't used require.js in a long time now.

ianstormtaylor avatar Sep 17 '13 22:09 ianstormtaylor

This is still a bug - supporting Require.js should be high on prio lists of any library IMO.

grimen avatar Oct 03 '13 15:10 grimen

I ran into this problem when trying to combine analytics.js and require.js. I'm not sure if there is any relevance to the original problem but thought I'd document my findings to save anyone else the effort should they run into the same problem I did.

I'm gradually upgrading a legacy site to utilize various javascript libraries. One of the things I had added was a script that gets added to every page which async appends the analytics.js script and then when loaded, initializes it.

When I tried to use require.js on one of my pages, I ran into the error listed above Mismatched anonymous define() module: function (){return require("analytics")}

After some digging I found that since analytics.js is AMD capable, if you both try to append the analytics.js script and then load requirejs it will fail with the error above.

In order to get around this issue I added the following around the script which loads and initalizes analytics.js

if(!(typeof define == "function" && define.amd))
{
...
}

I then instead initialize it in my main.js, which triggers require.js to load it instead.

define(['analytics'],
    function (analytics) {
        analytics.initialize({
            'AdRoll': {
                advId: 'XXX',
                pixId: 'XXX'
            }
        });
    });

DenisPitcher avatar Nov 10 '13 10:11 DenisPitcher

requirejs support would be greatly appreciated...

mistakia avatar Dec 09 '13 23:12 mistakia

For anyone still interested - the issue here is in the second AMD define call made by the segmentio-store.js/store.js lib. Once you make the fix below, you do not need to shim the module as the OP mentions above, as the library is AMD compatible.

You can fix it manually by commenting out the second AMD wrapper around line 11181:

require.register("segmentio-store.js/store.js", function(exports, require, module){

// Remove the amd wrapper
// ;(function(win){

  var store = {},

    // Add the 'win' reference
    win = this.window || global,
    doc = win.document,
    localStorageName = 'localStorage',
    namespace = '__storejs__',
    storage

  store.disabled = false
  store.set = function(key, value) {}
  store.get = function(key) {}
  store.remove = function(key) {}
  store.clear = function() {}
  store.transact = function(key, defaultVal, transactionFn) {
    var val = store.get(key)
    if (transactionFn == null) {
      transactionFn = defaultVal
      defaultVal = null
    }
    if (typeof val == 'undefined') { val = defaultVal || {} }
    transactionFn(val)
    store.set(key, val)
  }
  store.getAll = function() {}

  store.serialize = function(value) {
    return JSON.stringify(value)
  }
  store.deserialize = function(value) {
    if (typeof value != 'string') { return undefined }
    try { return JSON.parse(value) }
    catch(e) { return value || undefined }
  }

  // Functions to encapsulate questionable FireFox 3.6.13 behavior
  // when about.config::dom.storage.enabled === false
  // See https://github.com/marcuswestin/store.js/issues#issue/13
  function isLocalStorageNameSupported() {
    try { return (localStorageName in win && win[localStorageName]) }
    catch(err) { return false }
  }

  if (isLocalStorageNameSupported()) {
    storage = win[localStorageName]
    store.set = function(key, val) {
      if (val === undefined) { return store.remove(key) }
      storage.setItem(key, store.serialize(val))
      return val
    }
    store.get = function(key) { return store.deserialize(storage.getItem(key)) }
    store.remove = function(key) { storage.removeItem(key) }
    store.clear = function() { storage.clear() }
    store.getAll = function() {
      var ret = {}
      for (var i=0; i<storage.length; ++i) {
        var key = storage.key(i)
        ret[key] = store.get(key)
      }
      return ret
    }
  } else if (doc.documentElement.addBehavior) {
    var storageOwner,
      storageContainer
    // Since #userData storage applies only to specific paths, we need to
    // somehow link our data to a specific path.  We choose /favicon.ico
    // as a pretty safe option, since all browsers already make a request to
    // this URL anyway and being a 404 will not hurt us here.  We wrap an
    // iframe pointing to the favicon in an ActiveXObject(htmlfile) object
    // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
    // since the iframe access rules appear to allow direct access and
    // manipulation of the document element, even for a 404 page.  This
    // document can be used instead of the current document (which would
    // have been limited to the current path) to perform #userData storage.
    try {
      storageContainer = new ActiveXObject('htmlfile')
      storageContainer.open()
      storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
      storageContainer.close()
      storageOwner = storageContainer.w.frames[0].document
      storage = storageOwner.createElement('div')
    } catch(e) {
      // somehow ActiveXObject instantiation failed (perhaps some special
      // security settings or otherwse), fall back to per-path storage
      storage = doc.createElement('div')
      storageOwner = doc.body
    }
    function withIEStorage(storeFunction) {
      return function() {
        var args = Array.prototype.slice.call(arguments, 0)
        args.unshift(storage)
        // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
        // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
        storageOwner.appendChild(storage)
        storage.addBehavior('#default#userData')
        storage.load(localStorageName)
        var result = storeFunction.apply(store, args)
        storageOwner.removeChild(storage)
        return result
      }
    }

    // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
    var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
    function ieKeyFix(key) {
      return key.replace(forbiddenCharsRegex, '___')
    }
    store.set = withIEStorage(function(storage, key, val) {
      key = ieKeyFix(key)
      if (val === undefined) { return store.remove(key) }
      storage.setAttribute(key, store.serialize(val))
      storage.save(localStorageName)
      return val
    })
    store.get = withIEStorage(function(storage, key) {
      key = ieKeyFix(key)
      return store.deserialize(storage.getAttribute(key))
    })
    store.remove = withIEStorage(function(storage, key) {
      key = ieKeyFix(key)
      storage.removeAttribute(key)
      storage.save(localStorageName)
    })
    store.clear = withIEStorage(function(storage) {
      var attributes = storage.XMLDocument.documentElement.attributes
      storage.load(localStorageName)
      for (var i=0, attr; attr=attributes[i]; i++) {
        storage.removeAttribute(attr.name)
      }
      storage.save(localStorageName)
    })
    store.getAll = withIEStorage(function(storage) {
      var attributes = storage.XMLDocument.documentElement.attributes
      var ret = {}
      for (var i=0, attr; attr=attributes[i]; ++i) {
        var key = ieKeyFix(attr.name)
        ret[attr.name] = store.deserialize(storage.getAttribute(key))
      }
      return ret
    })
  }

  try {
    store.set(namespace, namespace)
    if (store.get(namespace) != namespace) { store.disabled = true }
    store.remove(namespace)
  } catch(e) {
    store.disabled = true
  }
  store.enabled = !store.disabled

  // Added this export call
  module.exports = store;

//   This is the other define call that wont work with r.js
//   if (typeof module != 'undefined' && module.exports) { module.exports = store }
//   else if (typeof define === 'function' && define.amd) { define(store) }
//   else { win.store = store }
// })(this.window || global);

});

chiplay avatar Jan 20 '14 15:01 chiplay