www.webdeveloper.com
Results 1 to 3 of 3

Thread: JavaScript 'include' function

  1. #1
    Join Date
    May 2012
    Posts
    1

    JavaScript 'include' function

    Hi all,

    I am a bit of a newb to JS and the forum.

    Was wondering if someone could help me:

    I am hoping that JavaScript has something similar to PHP's include() function whereby you can include another file as part of your page.

    IE: so I can write one html header and call it on each page I create, rather then having to repeat the same info per html file.

    Any help would be appreciated!

    Thanks

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    Code:
    01	function include( filename ) {  // The include() statement includes and evaluates the specified file.
    02	    // 
    03	    // +   original by: mdsjack (http://www.mdsjack.bo.it)
    04	    // +   improved by: Legaev Andrey
    05	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    06	    // +   improved by: Michael White (http://crestidg.com)
    07	    // %        note 1: Force Javascript execution to pause until the file is loaded. Usually causes failure if the file never loads. ( Use sparingly! )
    08	 
    09	    var js = document.createElement('script');
    10	    js.setAttribute('type', 'text/javascript');
    11	    js.setAttribute('src', filename);
    12	    js.setAttribute('defer', 'defer');
    13	    document.getElementsByTagName('HEAD')[0].appendChild(js);
    14	 
    15	    // save include state for reference by include_once
    16	    var cur_file = {};
    17	    cur_file[window.location.href] = 1;
    18	 
    19	    if (!window.php_js) window.php_js = {};
    20	    if (!window.php_js.includes) window.php_js.includes = cur_file;
    21	    if (!window.php_js.includes[filename]) {
    22	        window.php_js.includes[filename] = 1;
    23	    } else {
    24	        window.php_js.includes[filename]++;
    25	    }
    26	 
    27	    return window.php_js.includes[filename];
    28	}
    
    Example of use:  include('/js/imaginary1.js');

  3. #3
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,774

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles