Tip: Loading inline JS from file

Not really a surprise to real developers I guess but to me it was. The addInlineJs method allows you to read a chunk of Javascript from file.
This can be very useful if you need your plugin to insert some Javascript code in a page which is more than a single line.

So normally, as documented, for a single line of Javascript one would do:

$assets->addInlineJs('alert("Hello from My Plugin !")', 1);

But this works too:

$assets->addInlineJs(file_get_contents('user/plugins/my_plugin/alert.j s'), 1);

where the file alert.js contains:

alert("Hello from My Plugin !");

I know, in this overly simple one line example it doesn’t make sense but you get the point :slight_smile:

Sorry for the space in the second code block. I saw it while writing this post when the space was inserted by the editor of Muut the forum software. Couldn’t get rid of it. Strange.

Thanks! This is being added to the plugin cookbook in the in a future release.

No thanks! I’m very happy to be able to contribute to Grav although it’s just a tiny bit.

Thanks for pointing out the file_get_content trick.
Any idea if it’s possible to inject minified CSS with this approach?

$assets->addInlineCss(file_get_contents('mycustomstyles.css'), 1);will include the content of the file mycustomstyles.cssinline in the page’s HTML source. To insert minified CSS you should save a minified version of your CSS into the file.

@bleutzinn is there a way to create the “minified version of your CSS” file with Grav?
I set css_pipeline and css_minify to true, but that results in an external css file. The CSS I inject using addInlineCssremains non-minified.
I guess I’d need another “task” which minifies the inline CSS file, before I inject it inline. Can I do that with Grav? Or do I have to use other tools for it?

I don’t think you can do that with Grav. Do you really need the CSS inline? What is the benefit of having the CSS in the HTML over loading the CSS as part of the bundled and minified external CSS file? Just curious :slight_smile:

It’s Google’s PageSpeed requirements, they require to have at least the CSS for the elements above-the-fold in the first HTML response (=inline element in the section)