简体   繁体   English

是否可以插入和运行动态脚本标记?

[英]Is it possible to insert and run a dynamic script tag?

I have the following code in a cljs file: 我在cljs文件中有以下代码:

(def template 
    "<script type=\"text/javascript\">
      console.log(\"The script was run\");
    </script>")

(defn add-script []
  (let [s (js/document.createElement "div")]
    (set! (.-innerHTML s) template)
    (js/document.head.appendChild (.-firstChild s))))

(Obviously, the real script template's content is different than this, but this illustrates the problem) (显然,真实脚本模板的内容与此不同,但这说明了问题)

When I look in the document after add-script has been run, sure enough, the script template has been inserted into the code. 当我在运行add-script之后查看文档时,确定已将脚本模板插入到代码中。 The problem is that the code has not actually been executed. 问题是代码实际上没有被执行。 If this were just js, I would simply eval the template. 如果这只是js,我只需要评估模板。 However, Clojurescript does not have eval, so I thought I would try dynamically adding the content of the javascript template using a script tag. 但是,Clojurescript没有eval,所以我想我会尝试使用脚本标签动态添加javascript模板的内容。

How can I get this to work, specifically, how can I get these content of my script template to evaluate after I have dynamically inserted it? 我怎样才能使其工作,具体来说,在动态插入脚本模板之后,如何才能获得我的脚本模板的这些内容?

I've done something similar with this code 我用这段代码做了类似的事情

(let [the-head js/document.head
      the-script (.createElement js/document "script")
      the-script-value "console.log(\"The script was run\");"
      ]
  ; if you need to load a js file
  ;(set! (.-type the-script) "text/javascript")
  ;(set! (.-src the-script) "url_file")
  (set! (.-innerHTML the-script) the-script-value)  
    (.appendChild the-head the-script)
  )

I hope it helps you 我希望它对你有所帮助

(def template 
    "<script type=\"text/javascript\">
      console.log(\"The script was run\");
    </script>")

(defn add-script []
  (let [e (js/document.createElement "script")
        t (subs template 32 (- (count template) 14))]
    ;; t -> "      console.log(\"The script was run\");"
    (set! (.-text e) t)
    (js/document.head.appendChild e)))

Works. 作品。 I am actually quite surprised that this innerHTML behavior causes the code to not load. 我真的很惊讶这个innerHTML行为导致代码无法加载。 Seems inconsistent and does not make a great deal of sense to me. 似乎不一致,对我来说没有多大意义。

I would also appreciate a proper Clojurescript regular expression for grabbing the content in my script tag. 我还要感谢一个适当的Clojurescript正则表达式来抓取我的脚本标记中的内容。 I couldn't seem to find a working example of actually using regular expressions in cljs. 我似乎找不到在cljs中实际使用正则表达式的实际示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM