3030import os , socket , pkg_resources
3131import CodeChat .CodeToRest
3232from sphinx .errors import ExtensionError
33+ from sphinx .builders .html import JavaScript
3334
3435
3536# TODO: clean up - many of the folders are not needed as the files are imported by webpack
@@ -75,6 +76,26 @@ def runestone_extensions():
7576 modules .insert (0 , modules .pop (modules .index ("runestone.common" )))
7677 return modules
7778
79+ # setup_js_defer(app, pagename, templatexname, context, doctree)
80+ # -----------------------
81+ # Used to inspect js right before it is rendered to page so that
82+ # we can forcibly defer js files or prevent same
83+ def setup_js_defer (app , pagename , templatexname , context , doctree ):
84+ def js_defer (script_files ):
85+ for js in sorted (script_files ):
86+ if app .config .html_defer_js :
87+ # Files added from Runestone should already have defer set - so just add it to sphinx based ones
88+ to_defer = ["_static/jquery.js" , "_static/underscore.js" ,"_static/doctools.js" ]
89+ if isinstance (js , JavaScript ) and js in to_defer :
90+ js .attributes ["defer" ] = ""
91+ else :
92+ #config flag not set, prevent all deferrals
93+ if isinstance (js , JavaScript ):
94+ js .attributes .pop ("defer" , None )
95+ return ''
96+
97+ context ['js_defer' ] = js_defer
98+
7899
79100# setup(app)
80101# ----------
@@ -94,16 +115,18 @@ def setup(app):
94115
95116 for jsfile in script_files :
96117 try :
97- app .add_autoversioned_javascript (jsfile )
118+ app .add_autoversioned_javascript (jsfile , defer = "" )
98119 except ExtensionError :
99- app .add_js_file (jsfile )
120+ app .add_js_file (jsfile , defer = "" )
100121 for cssfile in _css_files :
101122 try :
102123 app .add_autoversioned_stylesheet (cssfile )
103124 except ExtensionError :
104125 app .add_css_file (cssfile )
105126
106127 app .config .html_static_path .append ("dist/" )
128+ app .add_config_value ("html_defer_js" , False , 'env' )
129+ app .connect ('html-page-context' , setup_js_defer )
107130
108131
109132def get_master_url ():
0 commit comments