問題描述
通過 JavaScript 在標題或 HTML 中動態包含腳本元素 (Dynamically include script element in header or HTML by JavaScript)
I have a script to the third party JavaScript library which requires token to be injected dynamically.
I was told to include script below into the head of my html. I need to replace {your_token} in order for this to work. However this token is only available at runtime so I need to inject this script into the header of my application at runtime (init for the application code)
<script>(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel={your_token}...
What is the best way to replace your_token with right token and inject this script at the header of the application?
參考解法
方法 1:
Just as Casey asked, it depends on where this script block come from?
Backend replacement
If you use any backend template engine, you probably have the opportunity to replace that token into the one you have in hand. So the output will be the script contains the real token the script needed.
Front end replacement
If you are using some template in front such as using handlebar template(other template engines works almost the same)
<script type="text/x‑handlebars‑template">your third party js code <token here></script>
, you can replacing the token when generating the dom element.
For me I prefer do this at backend.
方法 2:
Assuming that "this token is only available at runtime" means "from the onModuleLoad
" (for whichever reason), then you could have the script as a String
in your GWT app (you might want to use a ClientBundle
with the script in a TextResource
, or simply a String
constant in your code), replace {your_token}
with String#replace
and then inject the resulting script with the ScriptInjector.fromString
.
Though if you can, use "backend replacement" as proposed by Mike Li with a dynamic host page.
(by user_1357、Mike Li、Thomas Broyer)