views:

383

answers:

2

Please excuse me if I'm simple here, I want to create a simple widget that people can access from their websites - e.g by copy/past something like

<script language="javascript" src="test2.js"></script>
<div id="test"></div>

anywhere in their web pages. where is dynamically filled via Jquery and the functions in/on test2.js.

I can do it if JQuery is actually "printed" on the page of test2.js, but I cannot get any JQuery functions to work if I try to include/call JQuery dynamically. How do you call JQuery via javascript and then get it to work with the functions on the page?

And/Or is there an easy way to add the <div id="test"></div> dynamically aswell? Sure I can body.append etc. but that only adds at the bottom of the page. Is there a way to .append in the position where the script include

<script language="javascript" src="test2.js"></script>

is actually placed?

Hope I make sence.

+1  A: 
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

you jquery code should be placed at the bottom of the page now to wait for jquery library to be attached in the head

XGreen
A: 

Regarding your question whether <div id="test"></div> can be added dynamically at the position of the script:

If you call document.write in your script, then this content is inserted into the document after the script.

E.g.:

<html>
<head></head>
<body>
   <div id="first">
       <div id="second">
           <script type="text/javascript">
               document.write('<h2>test</h2>');
           </script>
      </div>
   </div>
</body>
</html>

results in

<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>
Felix Kling