How to load js file on demand

I want to load lightgallery javascript file if page contains image resource.
I can Use the .Store variable to set a flag to decide whether to load js resources.
themes\DoIt\layouts_default_markup\render-image.html

{{- .Page.Store.SetInMap "this" "lightgallery" $lightgallery -}}
{{- if (.Store.Get "this").lightgallery - }}
 <script src= "lib/lightgallery/lightgallery.min.css">

But How to load js file on demand on the home page? Because a scratch pad is attached to a Page object.
I considered checking whether there is an image in .Summary to decide whether to load the js file.
How to detect whether summary contains an image?

The method will be the same.

The Home page is also just a Page and rendered with templates defined by the template lookup order and rules.

See Home Templates

when I test it does not work, render-image.html and baseof.html are not on the same scope. Does the .Summary have a special handle?

I add this code:

themes\DoIt\layouts_default_markup\render-image.html

{{- $lightgallery := .Page.Params.lightgallery | default site.Params.Page.lightgallery | default false -}}
{{- .Page.Scratch.SetInMap "this" "lightgallery" $lightgallery -}}
{{- printf "this is %v on %v" (.Page.Scratch.Get "this") .Page.RelPermalink -}}
.....

themes\DoIt\layouts\partials\assets.html

{{- printf "assets this is %v on %v" (.Scratch.Get "this") .Page.RelPermalink -}}
{{- if $params.lightgallery | and (.Scratch.Get "this").lightgallery -}}

output on the homepage

this is map[lightgallery:true] on /post/videos-index-problem/

assets this is map[config:map[data:map[id-1:不要忘了,为何出发]] count:2 typeitMap:map[id-1:[id-1]]] on /

They are not on same page object

lot’s of partials involved, range, pagination, shortcodes, template …

with just these code snippets it’s impossible (see post on the topic) to track that down.

two general problems that could participate:

plus coding issues, plus …

Thank you for your reply. I will try