Since you want your plugin to be theme independent you will have to rely on hooks that you may assume isare there in aany decently made theme. At the moment you can only relayrely on wp_head
and wp_footer
. A hook right after the <body>
tag is under discussion, but even if it would be declared standard today, there would still be thousands of existing themes not implementing it. So that's no use for you.
The option you tried just buffers most of the page, letting you change the buffer's content before it is printed. It should work, though it is far from elegant and could easily interfere with other plugins using some kind of buffering.
So, no, there is no direct WordPressy way to do this in a reliable way. What you could do in a plugin, however, is solve it with json. The idea is fairly simple, though it will require some work (and probably a learning curve).
Hooking into wp_head
add a jquery script file that adds a DOM-element right after the <body>
tag and use the rest api to call the function that you would normally generate the code that you want in that place.