The thing you want to do is quite difficult. I had a lot of problems with synchronous AJAX requests to correctly load my javascript files dynamically.
Actually I implemented something that worked synchronously on my project which is the same as you want.
It is only possible if you have a server-side scripting engine (e.g. PHP) to generate your HTML page.
The idea is to parse the init-scripts.js on server side prior to include them into the html code.
Instead of writing echo <script type="text/javascript" src="js/init-script.js"></script> in my PHP script I write : JavascriptLoader::addJavascript('js/init-script.js');
JavascriptLoader is a PHP class which manages scripts to be loaded.
This addJavascript function parses the init-script.js and, each time it encounters a line which starts with "loadScriptMethod(",
- it parses and uses the string between brackets (e.g
loadScriptMethod('thisString')) as the scriptToLoad
- and then calls recursively
JavascriptLoader::addJavascript($scriptToLoad);
JavascriptLoader::addJavascript then do an echo '<script type="text/javascript" src="'.$scriptToLoad.'"></script>' to write
I cannot publish the JavascriptLoader code from my project, but here is a simplified example of PHP code:
class JavascriptLoader{
...
public static function addJavascript($filepath){
self::init(); //Init to write the javascript loadScriptMethod definition into HTML output
if (!self::isScriptAlreadyLoaded($filepath)){
self::parseFile($filepath);
echo '<script type="text/javascript" src="'.$urlScript.'"></script>',"\n";
self::ajouterScriptDejaCharge($chemin);
}
}
private static function parseFile($filepath){
if (file_exists($filepath)){
$lines = file($filepath, FILE_SKIP_EMPTY_LINES);
foreach($lines as $line){
$matches = array();
$test = preg_match ('/^loadScriptMethod\(\s*[\'\"](.+)[\'\"]\s*\)/' , $line , $matches);
if ($test > 0){
$scriptToLoad = $matches[1];
//On inclut le fichier
self::addJavascript($scriptToLoad);
}
}
}
else{
throw new Exception('javascript source file '.$filepath.' does not exist.');
}
This also stores the $scriptToLoad into an array to avoid loading twice the same script (functions isScriptAlreadyLoaded and addScriptToAlreadyLoadedList).