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...

1
  • 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. Commented Aug 27, 2016 at 4:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

How could I get the file from the html files when it's referenced from the package?
The package.js file loads all of you files. It's like an executable file.
So I could include the scripts in the 'scripts' section? But then what do I do? (sorry if this sounds daft)
I seriously don't understand the package.json approach to including .js files that index.html can use. Somebody please help?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.