2

I'm trying to add scripts to HTML files dynamically using JavaScript (to save space - I've many HTML files each of which contains many scripts, so they would al be added simply by including one script file).

The question Append javascript to HTML fields using through javascript is not really what I was thinking about...

However, in the script file that adds scripts and other resources to the HTML file in question, the scripts do add the external files, but the scripts (those inserted dynamically) are not loaded.

Directory Structure

root
 ├ index.html
 ├ universal-scripts.js (adds scripts to .html files dynamically)
 ├ styling.css (included into .html files)
 └ app-scripts
    └ others.js (problem file)

universal-scripts.js

...
var others = document.createElement("script");
others.setAttribute("src", "app-scripts/others.js");
...
document.getElementsByTagName("head")[0].innerHTML = document.getElementsByTagName("head")[0].innerHTML + others.outerHTML;

The script is inserting the element but functions from others.js are not usable from within index.html.

Any help would be much appreciated. Thanks!

I'm using Electron if that means anything...

Community
  • 1
  • 1
Theo
  • 548
  • 2
  • 8
  • 19
  • Have you considered a build tool like Gulp? It is a task runner that can, among many other things, find and combine many .js files into one file so that you can simply put them anywhere in your project directory and they will get loaded. – Nate Vaughan Aug 27 '16 at 04:02

1 Answers1

2

Probably the best way is to add the reference to the file in your package.js file since this is where all of the rest of your projects source file are referenced. Why load it latter when you can load it in your core.

Here is a Electron.js tutorial that talks about the package.js file.

Creating Your First Desktop App With HTML, JS and Electron]1

Here is a package.js interactive guide. package.js walk through

andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
  • How could I get the file from the html files when it's referenced from the package? – Theo Aug 27 '16 at 03:58
  • The package.js file loads all of you files. It's like an executable file. – andre mcgruder Aug 27 '16 at 04:44
  • So I could include the scripts in the 'scripts' section? But then what do I do? (sorry if this sounds daft) – Theo Aug 27 '16 at 04:47
  • I seriously don't understand the package.json approach to including .js files that index.html can use. Somebody please help? – Theo Aug 27 '16 at 07:55
  • 1
    There isn't a single "scripts" section. You can have a script element anywhere you like, such as at the end of the body. In that script element, just code a call to the "require" function. If you look at the Electron Quick Start example at electron.atom.io, this is exactly what's done there. – Marc Rochkind Aug 27 '16 at 14:19