Dynamically load Jquery into .js page
Please excuse me if I'm just here, I want to create a simple widget that people can get from their websites - for example, copy / skip something like
<script language="javascript" src="test2.js"></script>
<div id="test"></div>
anywhere on their web pages. where is dynamically populated via jQuery and functions in / on test2.js.
I can do this if the JQuery is indeed "printed" in the test2.js page, but I cannot get JQuery to work if I try to include / call JQuery dynamically. How do you call JQuery through javascript and then run it to work with functions on the page?
And / Or is there an easy way to add < div id="test"></div>
dynamically? Of course I can body.append etc., but this only adds to the bottom of the page. Is there a way to .append at the position where the script includes
<script language="javascript" src="test2.js"></script>
really posted?
Hope I can do it.
a source to share
Regarding your question, is it possible to dynamically add <div id="test"></div>
to the position of the script:
If you call document.write
in a script, then this content is inserted into the document after the script.
eg:.
<html>
<head></head>
<body>
<div id="first">
<div id="second">
<script type="text/javascript">
document.write('<h2>test</h2>');
</script>
</div>
</div>
</body>
</html>
leads to
<html>
<head></head>
<body>
<div id="first">
<div id="second">
<script type="text/javascript">
document.write('<h2>test</h2>');
</script>
<h2>test</h2>
</div>
</div>
</body>
</html>
a source to share
function loadjscssfile(filename, filetype) {
if (filetype == "js") { //if filename is a external JavaScript file
var fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref != "undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("jquery-1.4.2.js", "js") //dynamically load and add this .js file
jquery code should be placed at the bottom of the page to wait for the jquery library to be attached in the head
a source to share