1

I’m building a Wordpress theme for Themeforest. In the customizer I’ve given users the ability to also use the rem unit for their font sizes. I’ve created three different settings that control the font-size on the html or :root element for three different media queries.

When I add the code for the :root or html in (1) a stylesheet or (2) wp_add_inline_style, the computing of the styles via the Browser takes too much time. The browser first renders all the text as if the rem size is 16px and after a second all the fonts scale to the correct size. This looks terrible. I only encountered this on Safari on iOS. (Is this a common problem? I can't find other people experiencing this on the internet...)

The only solution to this problem is when I manually add a tag before the wp_head() action. In this way, the styles are loaded so early that the browser does compute them correctly. Adding the CSS in this location greatly improves the user experience.

Themeforest has the requirement that inline css is not allowed, except for background-images. Wp_add_inline_style is allowed. Is it possible to add a <style> tag in such a way to the <head> with wp_add_inline_style, that it is the first element before wp_head or the first element in wp_head?

Thanks!

1 Answer 1

2

Yes, that should be doable. Just enqueue your inline styles with callback hooked to wp_enqueue_scripts and priority set to 0 (assuming other styles are loader later / lower priority / bigger number). You also need to register a dummy handle to which you attach the inline styles to, so no other styles are loaded before them.

function my_pre_theme_assets() {
    wp_register_style( 'dummy-handle', false );
    wp_enqueue_style( 'dummy-handle' );
    wp_add_inline_style( 'dummy-handle', '* { color: red; }' );
}
add_action( 'wp_enqueue_scripts', 'my_pre_theme_assets', 0 );

Dummy handle idea seen here, wp_add_inline_script without dependency

2
  • Hi Antti, thank you for your solution! I didn’t know about the priority, so you’ve certainly be helpful.
    – ralphjsmit
    Jul 25, 2020 at 20:03
  • 1
    @ralphsmit Both add_action() and add_filter() take up to four arguments. 1st the target hook, 2nd your callback function, 3rd priority and 4th number of parameters the callback recieves. You can read more about hooks here, developer.wordpress.org/plugins/hooks Jul 26, 2020 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.