Home

CClientScript positioning

Published on 6/29/2011


CClientScript is useful for including css files and javscript files, while avoiding duplication.

Things to know:

  1. Yii injects css files just above the tag. So, if you want to always override some included yii style, put your <styles> or <link rel=stylesheets> AFTER the <title> tag, and it will get loaded after the yii styles.</p> </li> <li> <p>I recommend putting all your <styles> and <link rel=stylsheets> in the <head> and all your <scripts> just before </body>. <scripts> are blocking, so your page will load faster if the <scripts> are at the bottom. use:</p> </li> </ol> <p>Yii::app()->getClientScript()->coreScriptPosition = CClientScript::POS_END;</p> <ol start="3"> <li>if you want to include some inline javascript in a view, but make it load at the bottom, after say jquery, use the registerScript() method. To format your js nicely, you can use the <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc">Heredoc</a> syntax:</li> </ol> <p>/* load some formatted js into a php variable: */<br> $js = <<<EOF<br> var = ‘some javascript here!’;<br>     function() { return ‘you can format it as you like, and include php $variables’; };<br> EOF;</p> <p>/* write the script at the bottom of the document  */<br> Yii::app()->getClientScript()->registerScript(“some id”, $js, CClientScript::POS_END);</p> <span id="goatcounter-views">... views</span><script>(function(){const path = undefined; const goatcounterCode = "neilcv"; if (goatcounterCode) { let targetPath = path || window.location.pathname; if (targetPath.length > 1 && targetPath.endsWith("/")) { targetPath = targetPath.slice(0, -1); } const endpoint = `https://${goatcounterCode}.goatcounter.com/counter/${encodeURIComponent(targetPath)}.json`; fetch(endpoint) .then((res) => { // If path has 0 visits recorded yet, GoatCounter returns 404 if (res.status === 404) return { count: 0 }; if (!res.ok) throw new Error("Network error"); return res.json(); }) .then((data) => { const el = document.getElementById("goatcounter-views"); if (el) el.textContent = `${data.count ?? 0} views`; }) .catch(() => { const el = document.getElementById("goatcounter-views"); if (el) el.textContent = ""; }); } })();</script><section class="giscus-container" data-astro-cid-nuen6n26><script src="https://giscus.app/client.js" data-repo="neilmcguigan/neilcv-comments" data-repo-id="R_kgDOUEIj9Q" data-category="General" data-category-id="DIC_kwDOUEIj9c4DELe8" data-mapping="pathname" data-strict="0" data-reactions-enabled="1" data-emit-metadata="0" data-input-position="bottom" data-theme="preferred_color_scheme" data-lang="en" crossorigin="anonymous" async></script></section></div></main><footer></footer></body></html>