I'm aware of the procedure to add a script with document.createElement('script')
but is it just the same for a local file? I've tried using a few function.toString()
calls but that's terribly inefficient and would rather store the file I need to add separately, have a loader, and call it a day. Any ideas? This is all for a user script I hope to flawlessly convert into an extension. Thanks.
Asked
Active
Viewed 1,600 times
1

Gabriel Ryan Nahmias
- 2,135
- 2
- 26
- 39
1 Answers
1
Setting the <script>
src
to the local file works. EG:
addJS_Node (null, 'file:///D:/SAMPLE_DIR/YOUR_CODE.js');
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
//--- Don't error check here. if DOM not available, should throw error.
targ.appendChild (scriptNode);
}
Important: You almost always have to specify the full path, because you want your files to load off of the local filesystem. The browser would interpret a relative path as relative to the current webpage (or <base>
tag value).
Re:
This is all for a user script I hope to flawlessly convert into an extension
For extensions, it is almost always better to not inject your JS into the target page, but to keep it in the "isolated world" scope.
For extensions, or sometimes even just dedicated Chrome userscripts, easily include files into that scope using the manifest. EG (from here):
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"]
}
],
...
}

Community
- 1
- 1

Brock Adams
- 90,639
- 22
- 233
- 295
-
Oops! Sorry about that. In this context you cannot include a local file via a relative path. You need the full `file:///D:/ ...` URL. ... ... The manifest stuff does not apply until you write an extension, or unless you set up your *Chrome userscript* as shown [in this answer](http://stackoverflow.com/a/5259212/331508). – Brock Adams Jun 10 '12 at 04:34