Yes, instead of updating the inline style
for the elements directly, a stylesheet should be used instead. You can create a stylesheet template that is used both in JS and in PHP. This was done in the Twenty Sixteen theme and I actually just worked on this in a standalone example plugin for another answer.
Notice how there is a stylesheet_template
string that is created, and this template string is rendered out by PHP at the wp_print_styles
action:
/**
* Print styles.
*/
public function print_styles() {
echo '<style id="wpse-286268" type="text/css">';
$css = $this->stylesheet_template;
$tpl_vars = array();
foreach ( $this->device_configs as $slug => $params ) {
$tpl_vars[ '{{outline_color_' . $slug . '}}' ] = get_theme_mod( "outline_color_{$slug}", $params['default'] );
}
echo esc_html( str_replace(
array_keys( $tpl_vars ),
array_values( $tpl_vars ),
$css
) );
echo '</style>';
}
And then also it is rendered out by JS in the customizer preview:
/**
* Update preview.
*
* @returns {void}
*/
component.updatePreview = function updatePreview() {
var css = component.stylesheetTemplate;
_.each( component.deviceSettings, function( setting ) {
css = css.replace( '{{' + setting.id + '}}', setting.get() );
} );
component.style.text( css );
};