I tried to register a raw Javascript in this way:
Yii::app()->clientScript->registerScript('myscript', '//Javascript here');
but it didn’t work. The registerScript only seems to work with jQuery. Is that true or am I wrong?
I tried to register a raw Javascript in this way:
Yii::app()->clientScript->registerScript('myscript', '//Javascript here');
but it didn’t work. The registerScript only seems to work with jQuery. Is that true or am I wrong?
You are mistaken. And, jQuery is javascript too.
Is it possible to register google analytics code like this?
Yii::app() -> clientScript -> registerScript('analytics', '
var _gaq = _gaq || [];
_gaq.push([\'_setAccount\', \'UA-33333934-4\']);
_gaq.push([\'_trackPageview\']);
(function() {
var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;
ga.src = \'/js/ga.js\';
var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);
})();
');
Yes, it should be done like that.
I’ve just tried to register analytics code but it’s not working!!!
I’ve checked the code for registerScript - I wasn’t aware that defaultScriptPosition is CClientScript::POS_READY, as in
registerScript($id,$script,$position=null,array $htmlOptions=array())
And with CClientScript::POS_READY the script is inserted in the jQuery’s ready function.
jQuery(function($) {
...
});
So to make sure you have got the plain js use
Yii::app()->clientScript->registerScript('name', 'js code here', CClientScript::POS_END);
or CClientScript::POS_BEGIN or CClientScript::POS_HEAD.
Brilliant, it worked!