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

时间:2013-07-18 06:49:35

标签: javascript html clojurescript

我在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))))

(显然,真实的脚本模板的内容与此不同,但这说明了问题)

当我在运行add-script之后查看文档时,确定已将脚本模板插入到代码中。问题是代码实际上没有被执行。如果这只是js,我只需要评估模板。但是,Clojurescript没有eval,所以我想我会尝试使用脚本标签动态添加javascript模板的内容。

我怎样才能让它工作,具体来说,在动态插入脚本模板之后如何才能获得我的脚本模板的这些内容?

2 个答案:

答案 0 :(得分:1)

我已经用这段代码做了类似的事情

(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)
  )

我希望它可以帮到你

答案 1 :(得分:0)

(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)))

作品。我真的很惊讶这个innerHTML行为导致代码无法加载。似乎不一致,对我来说没有多大意义。

我还要感谢一个正确的Clojurescript正则表达式来抓取我的脚本标记中的内容。我似乎无法找到在cljs中实际使用正则表达式的实际示例。