/    Sign up×
Community /Pin to ProfileBookmark

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

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@PadonakMay 24.2012 — [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 }

[B]Example of use[/B]: include('/js/imaginary1.js');
[/CODE]
Copy linkTweet thisAlerts:
@toicontienMay 25.2012 — Check out load.js.
×

Success!

Help @MeltingDog spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...