Conditional Custom Action Script Links

We noticed an issue today where because we were using a Custom Action, a script was being loaded on admin pages (I will refer to these as system pages here on in) and this caused an error.

We wanted this script to load on all pages and we loved the fact it was automatically injected by the CA but we didn’t want it to happen on system pages (site settings, site contents etc..).

So, I set about working out how you could implement a ‘conditional’ custom action (moving it to the master page was not an option). First off, take a look at our custom action elements declarative xml:

Nothing unusual there, but like I said before, we don’t want to document write out the script link if we are on a system page. The answer to this problem is quite simple. We can make sure that we have a unique identifier on the non-system pages (like a class on the body tag) and then check for it before writing out the script link.

So, on the client project I am currently working on, we have a custom master page for our site collections but we revert to the OOB Seattle master page on system pages. So, simply adding a ‘custommaster’ class to the body tag on our custom master page, we can now use this in deciding if we want to run our script from our Custom Action. We do this by amending the ‘Script Block’ in the Custom Action to only document write the script link if the body class is present. Simples.

The only thing to note about this approach is that we do not want to use jQuery in our conditional statement because there is no way to guarantee that it is readily available at the time we would need to use it. So we revert back to the 90’s and use good old raw javascript. The final version of our Custom Action can be found below (with the changes in bold):

Conditional Custom Action Script Links

Leave a Reply

%d bloggers like this: