Injecting Scripts without the javascript Type

Stop MODX from inserting type="text/javascript" when injecting scripts


MODX Forum user justinet pointed out that the $modx->regClientStartupScript() and $modx->regClientScript() methods add type="text/javascript" to the script tags. In this article, we'll look at a way around that.

MODX logo

The Problem

When you add JavaScript code to a page with one of the MODX regClient...() methods, MODX adds type="text/javascript" to the opening script tag:

<script type="text/javascript"> ... </script>

The type specification is harmless, but it's not correct in HTML5. If you validate your code (and it's a very good idea to do so), the validator will complain with something like this:

Warning: The type attribute is unnecessary for JavaScript resources.

The value of this tip may be short-lived. By the time you read this, MODX may have been modified so that it no longer adds the type specification. The fix is quite simple, though, and doesn't require any modifications to the core code, so it will still work fine after the code is updated.


The Solution

One of the reasons I love MODX is the forethought you see in its code. When I first saw the documentation on the regClient...() methods for scripts, I thought I would have to remember whether or not I should include tags myself or expect MODX to insert them. It turned out that I don't have to remember, though, because MODX looks at the code you're submitting and adds the script tags *only* if they're missing.

The solution, then, is to simply surround your code with tags (without the type specification) and MODX will inject them without modification. The only drawback of this method is that if the code you're injecting with regClient() references a .jsfile, adding the script tags will make your code editor think the JavaScript is invalid.

One solution is to rename the file extension to .html. A good code editor will still validate the JavaScript for you because it's enclosed in script tags.

Another solution I often use is to put the JavaScript containing the script tags in a chunk. Then you can use code like this to inject it:

$modx->regClientStartupScript($modx->getChunk('chunkName'));

Coming Up

In the next article, we'll look at a trick for selecting the language used by a MODX extra package.



Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)


      Previous Article << —— >>

Comments (0)


Please login to comment.

  (Login)