I want to include JS file inside another JS file, on server side, to prevent copy-paste and multiple JS files loading from client. Just like include('file.js') as PHP would do.
- Thanks for the answers but I just want it to be done on server, with one single javascript file load from client. I'd rather turn .js into .php (or rewrite) and use PHP include and then header('content-type:text/javascript). Any other solutions?Moe Sweet– Moe Sweet2011-10-14 08:32:37 +00:00Commented Oct 14, 2011 at 8:32
4 Answers
There is no built in way to include other JavaScript files from a JavaScript file ... but you can add them into the DOM ->
function addJavascript(jsname,pos) { var th = document.getElementsByTagName(pos)[0]; var s = document.createElement('script'); s.setAttribute('type','text/javascript'); s.setAttribute('src',jsname); th.appendChild(s); } Example usage :
addJavascript('newExternal.js','body'); 1 Comment
As Supercharging javascript article suggest - with PHP you can read all your .js files and create one big js file that you will send in one piece.
This is a simplification of the example from the article, just to get you started:
<?php define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/'); $files = array( 'jquery.js', 'myLib.js', 'site.js' ); header('Content-Type: text/javascript'); foreach (files as $file) { if (@readfile(SCRIPT_DIR . $file) === false) { error_log("javascript.php: Error reading file '$file'"); } } ?> I would also recommend to read the full article Supercharging JavaScript in PHP to get more info.
1 Comment
You will have to use a script loader and i would like to recommend script.js by Dustin Diaz who works at Twitter. Project Page on Github. Here is how you use it assuming you have a jquery plugin to be loaded in a page here is what you should do
// load jquery and plugin at the same time. name it 'bundle' $script(['jquery.js', 'my-jquery-plugin.js'], 'bundle') // load your usage $script('my-app-that-uses-plugin.js') /*--- in my-jquery-plugin.js ---*/ $script.ready('bundle', function() { // jquery & plugin (this file) are both ready // plugin code... }) /*--- in my-app-that-uses-plugin.js ---*/ $script.ready('bundle', function() { // use your plugin :) }) example is also from project page. Here are steps you should follow
- Load the Script.js file first
- Now include the dependency loader script that loads all the other wanted scripts async[the content of dependency loader script would be like above]