Gabriel Ryan Nahmias
Gabriel Ryan Nahmias

Reputation: 2159

Add Local JavaScript File to Page?

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.

Upvotes: 1

Views: 1724

Answers (1)

Brock Adams
Brock Adams

Reputation: 93533

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"]
        }
    ],
    ... 
}

Upvotes: 1

Related Questions