import gradio class JavaScriptLoader: def __init__(self, target): #Copy the template response self.original_template = gradio.routes.templates.TemplateResponse #Prep the js files self.load_js(target) #reassign the template response to your method, so gradio calls your method instead gradio.routes.templates.TemplateResponse = self.template_response def load_js(self, target): with open(target, 'r', encoding="utf-8") as file: self.loaded_script = f"" def template_response(self, *args, **kwargs): """Once gradio calls your method, you call the original, you modify it to include your scripts and you return the modified version """ response = self.original_template(*args, **kwargs) response.body = response.body.replace( ''.encode('utf-8'), (self.loaded_script + "\n").encode("utf-8") ) response.init_headers() return response