Greasemonkey Tip: Adding CSS With GM_addStyle

Adding style to a webpage with Greasemonkey is extremely easy, but I have noticed a lot of userscript code that either ignores the GM_addStyle( css ) api method, or doesn't use E4X which would save the author's time typing, and save the reader's time reading. So the following are some tips when adding CSS to a webpage with Greasemonkey.

Tip 1: Use GM_addStyle( css )

Don't add multiple style attributes, don't use that code you have that adds a style tag to the page, use the built-in GM_addStyle( css ) api method; usually you should only need to call this method it once.

Tip 2: Use E4X

Typically when your adding css to a page, there are quite a few lines, and you don't want to escape every newline character, or join a bunch of partial strings together; the simplest way to go is to use E4X like so:

GM_addStyle((<><![CDATA[
   body { color: white; background-color: black }
   img { border: 0 }
   .footer {width:875px;}
]]></>).toString());
© Erik Vold 2007-2012. Contact Erik Vold. Top ^