Error when using YUI3: "Y.QueryString.parse is not a function"

920 Views Asked by At

I'm building a Squarespace page, and I want to have an outgoing link on the page whose query parameters are set according to query parameters on the page itself. Since Squarespace embeds YUI3 in every site automatically, I'm trying to use that (even though I have more experience with jquery).

Example: The page is loaded as http://example.com/page/[email protected]. I have a link on the page that goes to http://another.example.com/page which should be modified to go to http://another.example.com/[email protected].

The following code does exactly what I need when I paste it in the browser console:

var MyButton = Y.all('a[href="http://another.example.com/page"]');
var QueryString = Y.QueryString.parse(window.location.search.substring(1));
MyButton.setAttribute('href','http://another.example.com/page?address=' + QueryString.email);

However, when I put that code in the page source, then when the page loads, the following error appears in the console: Uncaught TypeError: Y.QueryString.parse is not a function

My current theory is that YUI3 loads asynchronously in pieces, and this code runs at a point when Y.all is available but Y.QueryString.parse is not... is that right? What would be the best solution to this?

1

There are 1 best solutions below

0
François-Xavier Aeberhard On

Yui3 is indeed built around asychonous modules loading, in this case you miss the querystring module.

You need to wrap your code with a Y.use call:

Y.use('querystring', function(Y) {
  var MyButton = Y.all('a[href="http://another.example.com/page"]');
  var QueryString = Y.QueryString.parse(window.location.search.substring(1));
  MyButton.setAttribute('href', 'http://another.example.com/page?address=' + QueryString.email);
});