How do I load a javascript file dynamically?
This question already has an answer here:
You cannot embed HTML in Javascript in that way. Basically, what you want is to embed a script element, pointing to a certain javascript file when clicking a button. That can be done with combining events with DOM:
<script type="application/javascript">
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
</script>
<button onclick="loadJS('file1.js');">Load file1.js</button>
<button onclick="loadJS('file2.js');">Load file2.js</button>
试试这个大小:动态加载JS
function loadjscssfile(filename){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("myscript.js") //dynamically load and add this .js file
JavaScript:
function loadScript(url)
{
document.body.appendChild(document.createElement("script")).src = url;
}
function loadDefaultScript()
{
loadScript("http://mysite.com/file1.js");
}
function loadAlternateScript()
{
loadScript("http://mysite.com/file2.js");
}
HTML:
<input type="button" onclick="loadAlternateScript()" value="Alternate" />
<input type="button" onclick="loadDefaultScript()" value="Default" />
链接地址: http://www.djcxy.com/p/42454.html
下一篇: 如何动态加载JavaScript文件?