Yii2: JS scripts registered with registerJs() should get their own <script> tags

Created on 14 Feb 2018  路  4Comments  路  Source: yiisoft/yii2

If you register multiple JS scripts with yii\web\View::regsiterJs() at the same position, they will get imploded together and placed in a single <script> tag in the rendered HTML.

That results in a system that is generally more fragile 鈥撀爄f any script has an error, JS will stop executing for that context. This could be as simple as forgetting to end the script with a semicolon, which can cause the JS interpreter to get confused in some cases.

Putting each script in its own <script> tag would be a very easy way to make the system more robust, with very little performance cost. It would also give regitserJs() the ability to have an $options argument like registerCss() has, which would resolve #11018.

enhancement

Most helpful comment

If there is an error in JS then wouldn't you want to know it ASAP? It's fastest way to spot a problem if all JS stops working. If only small part of it is not working then spotting the problem is much harder.

All 4 comments

If there is an error in JS then wouldn't you want to know it ASAP? It's fastest way to spot a problem if all JS stops working. If only small part of it is not working then spotting the problem is much harder.

I disagree, and so do browsers. It鈥檚 not like an error in one context will halt JS execution for the entire page, which seems to be what you鈥檇 want? If that鈥檚 how browsers worked, half of the web would stop working.

Either way you will get a JS error in the console, so you can identify the issue, which is the most important thing.

If you are calling registerJs() twice, it is for two different scripts, and separate <script> tags is how you communicate that to the browser, so it knows to execute them separately.

Another problem is that different registerJs() scripts can use same variable/function names that will conflict if they are in the same scope. This is +1 pro to separate registerJs() scripts from each other.

PRs could not be moved but I've left a link in the issue moved to yiisoft/view.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MUTOgen picture MUTOgen  路  3Comments

Kolyunya picture Kolyunya  路  3Comments

Locustv2 picture Locustv2  路  3Comments

SamMousa picture SamMousa  路  3Comments

indicalabs picture indicalabs  路  3Comments