原生js动态注入脚本内容

JavaScript018

原生js动态注入脚本内容,第1张

export  const createScript = (result,type,pos) =>{

        var positions = pos? document.getElementsByTagName('head')[0] :document.getElementsByTagName('body')[0]

        var script = document.createElement('script')

        script.type = 'text/javascript'

        if (type === 'url') {

            script.src = result

        } else {            

            script.innerHTML = result

        }

        positions.appendChild(script)

    }

let scriptCode = `

            function fns(){

                alert("原生js动态注入脚本内容")

            }

            fns()

createScript(scriptCode)          

如果需要用原生js动态的加载另外一个js文件,可以使用原生js的document.createElement方法创建script节点,然后更改该节点的type和src属性,最后通过appendChild方法将该节点动态添加到html中,这样就可以了,参考代码如下:

var new_element = document.createElement("script")//创建新的script节点new_element.setAttribute("type", "text/javascript")new_element.setAttribute("src", "../js/jquery.js")document.body.appendChild(new_element)//添加到body节点的末尾

上例中是在body的最末尾添加的,当然同样可以在head中添加引用该js的标签:document.head.appendChild(new_element)