How to load script conditionally on custom field in wp_postmeta?

I’m trying to tidy up some of the code that has been doing its job for quite a while. Specifically, I used to load scripts in header.php and I’m trying to move that into functions.php.

One of the scripts should be loaded only for pages with a certain value in wp_postmeta. Precisely, if and only if this table has the value true for meta_key "mathjax", the mathjax script should be loaded.

In header.php I used

function my_init() {
    if (!is_admin()) {
        $mathjax = get_post_meta($post->ID,'mathjax',true);
            if($mathjax == 'y'){

add_action('init', 'my_init');

Now, this code doesn’t work in functions.php because $post is undefined. Can I still move this code into functions.php and if so, how can I make it work?

Solutions Collecting From Web of "How to load script conditionally on custom field in wp_postmeta?"

If you use $post in a function, you have to define it of course:

function xyz(){
    global $post;
    //Your code

Initial answer, might help others:
It appears to me, you do not use it inside an action or if so, you use it to early. It should work inside the ‘init’ action. So you could do something like

add_action( 'init', 'enqueue_conditionally' );
function enqueue_conditionally(){
    $mathjax = get_post_meta( get_the_ID(),'mathjax',true);
    if($mathjax == 'y'){