Forum Moderators: open

Message Too Old, No Replies

JSI java script includes

         

The_Hat

7:06 pm on Oct 17, 2007 (gmt 0)

10+ Year Member



I need to include a file from one of my sites into another of my sites on a seperate server.. without PHP... I understand I can pull in an external file like this using javascript but havent been able to find a sample code snipet as of yet.. anybody care to toss me some code?

Thanks in advance to help you can give.

Achernar

8:03 pm on Oct 17, 2007 (gmt 0)

10+ Year Member Top Contributors Of The Month



var j=document.createElement('script'); 
j.type='text/javascript';
j.src='http://example.com/js/yourJSfile.js';
j.id='scriptappended';
with(document.getElementsByTagName('head')[0]){
appendChild(j);
removeChild(j); // this line only if you don't want to leave a trace in the DOM tree
}

The content of the loaded javascript file will be executed as soon as the file has been loaded by the browser.

You can add an .onload attribute to the "j" object if you need your main script to be notified of the loading.

The_Hat

8:31 pm on Oct 17, 2007 (gmt 0)

10+ Year Member



TO clairify what I want to do is replicate this statement from php in javascript

<?php include("http://www.example.com/header.php");?>

So that i can use it to include a file (a page,naviation, ad rail, content rail, etc) on my other website that isn't php..

Achernar

9:21 pm on Oct 17, 2007 (gmt 0)

10+ Year Member Top Contributors Of The Month



If you include directly from the html page, use this:

<script type="text/javascript" src="yourScriptFile.js"></script>

You need at least one <script> tag in you document to execute some javascript code.

If you want to include other javascript files at "runtime" without having to modify your html source code, the example code I given above is the solution.

function include(f,ol) { 
var j=document.createElement('script');
j.type='text/javascript';
j.src=f;
if (ol) j.onload=ol;
document.getElementsByTagName('head')[0].appendChild(j);
}

where "ol" is the javascript code you want to execute after the include has completed

Now, if what you want is to include some html code from another page, the solution is probably ajax.

[edited by: Achernar at 9:23 pm (utc) on Oct. 17, 2007]