What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To load JavaScript from a URL in Go, fetch the URL with Go’s net/http package, read and validate the response, then pass its source text to a JavaScript runtime such as Goja. These are separate operations: Go fetches the file; Goja evaluates it. Evaluating JavaScript this way does not automatically provide a browser DOM, browser fetch, or Node.js globals.
What “load JavaScript from a URL” means in Go
Go does not execute JavaScript merely because you give it a URL. A typical server-side implementation has two stages:
- Fetch: make an HTTP request and obtain the response body as source text.
- Evaluate: give that source to an embedded JavaScript engine, such as Goja’s
Runtime.RunString.
The distinction matters. The Goja API executes source text; it does not fetch the URL for you. Likewise, a successful HTTP response does not guarantee that the returned content is JavaScript, syntactically valid, compatible with the runtime, or safe to execute.
The example below is a complete command-line program. It fetches a script over HTTP or HTTPS, rejects non-success status codes, reads at most a configured amount plus one byte to detect oversize responses, and evaluates the source with Goja. It requires Go and network access to download the Goja module.
#1 Best Overall
Runnable example: fetch a script and run it with Goja
1. Create a Go module
In an empty directory, initialize a module and add Goja:
go mod init example.com/loadscript
go get github.com/dop251/goja
2. Save and run the program
Save this as main.go. The URL is supplied as the first command-line argument, which avoids baking a remote script address into the program.
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/dop251/goja"
)
const maxScriptBytes int64 = 2 << 20 // 2 MiB
func fetchAndRun(ctx context.Context, client *http.Client, scriptURL string) error {
parsed, err := url.ParseRequestURI(scriptURL)
if err != nil {
return fmt.Errorf("parse script URL: %w", err)
}
if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Hostname() == "" {
return fmt.Errorf("script URL must be an absolute HTTP or HTTPS URL")
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("fetch script: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("fetch script: unexpected HTTP status %s", resp.Status)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxScriptBytes+1))
if err != nil {
return fmt.Errorf("read script response: %w", err)
}
if int64(len(body)) > maxScriptBytes {
return fmt.Errorf("script response exceeds %d bytes", maxScriptBytes)
}
// This example assumes the response body is UTF-8 JavaScript source.
// Add content-type and encoding policy if your application needs it.
vm := goja.New()
value, err := vm.RunString(string(body))
if err != nil {
return fmt.Errorf("evaluate script: %w", err)
}
fmt.Printf("Script result: %vn", value.Export())
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "usage: %s https://example.com/script.jsn", os.Args[0])
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
client := &http.Client{
Timeout: 15 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return fmt.Errorf("stopped after too many redirects")
}
return nil
},
}
if err := fetchAndRun(ctx, client, strings.TrimSpace(os.Args[1])); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Run it with a script URL you trust:
go run . https://example.com/script.js
Here the final JavaScript expression’s value is printed using Goja’s Export(). A script that only declares functions or produces no useful final value may print an undefined-like result; that does not by itself mean evaluation failed. The example treats the response as UTF-8 source and checks HTTP status, but it does not require a particular Content-Type. If your application needs stricter handling, validate the response media type and encoding before evaluation.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Using a function defined by the script
If the fetched source defines a global function, Go can retrieve and invoke it after RunString. For example, after evaluation, retrieve a function named calculate with Goja’s AssertFunction(), check that the assertion succeeded, invoke it with the runtime’s RunString result context as appropriate, and handle the returned error. Goja also documents Runtime.ExportTo() for converting JavaScript values into Go values. The exact conversion depends on the function’s arguments and return type, so define and validate that contract rather than assuming every JavaScript value maps directly to a Go type. See the Goja package documentation.
Choose the runtime based on what the script expects
Goja describes itself as an ECMAScript/JavaScript engine in pure Go. It executes supplied JavaScript and lets Go exchange values with the runtime. That is not the same environment as loading a <script src="..."> in a web browser.
- Plain JavaScript logic: Goja may fit if the script’s syntax and required APIs are supported.
- Browser-dependent code: scripts that access
window,document, DOM elements, or browser APIs need those capabilities from a suitable host. Goja does not become a browser simply by evaluating a script. - Node-dependent code: code that expects Node.js modules or globals needs a compatible environment or host integrations. Goja’s documentation points to a separate project for Node.js functionality; do not assume Node APIs are built in.
- Compatibility edge cases: Goja’s project documentation notes that some Annex B functionality is missing. Check the specific syntax and globals your source uses against the runtime you select.
For the primary implementation and API details, consult the Goja project repository and its package documentation.
Rank #4
Security: fetching remote code is a trust decision
A remote JavaScript file is executable code. Once evaluated, it can use capabilities that the application exposes to its runtime. Do not treat a URL allowlist check or an embedded engine as a complete sandbox. Decide who controls the URL, what the script is allowed to do, and how much time and memory the work can consume.
Constrain the fetch
- Apply URL policy: the example accepts only absolute HTTP and HTTPS URLs. A production service that accepts user-supplied URLs should also consider host allowlists and private, loopback, or link-local IP targets to reduce server-side request forgery risk. Validate destinations in a way that accounts for DNS resolution and redirects; checking only the original string is not a complete defense.
- Set a deadline: the example ties the request to a context and configures an HTTP client timeout. Choose limits based on the application rather than leaving outbound requests unbounded.
- Control redirects and transport: the example caps redirect hops, but security-sensitive applications may need to validate every redirect destination and configure DNS, proxy, TLS, and connection behavior deliberately. Go’s HTTP package documents the client and transport APIs at the net/http package reference.
- Bound the response:
io.LimitReaderreads no more than the configured maximum plus one byte, allowing the program to reject an oversized body instead of silently evaluating a truncated script. Set the maximum for your use case. - Check the response: non-2xx statuses are rejected. Applications can additionally enforce expected content types, allowed encodings, and integrity or signature requirements.
Constrain execution too
Network timeouts do not limit JavaScript execution time. Goja’s documentation includes an interruption mechanism, which can be useful for stopping a non-terminating script, but an interruption example is not proof that embedding a runtime alone makes untrusted code safe. Set an execution policy, use interruption or other controls where appropriate, and consider process-level resource isolation for hostile or high-risk scripts. Avoid exposing powerful Go functions, credentials, filesystem access, or unrestricted networking to a runtime unless the script is trusted and those permissions are intentional.
Best Value
Common failures and how to fix them
| Symptom | Likely cause | What to check |
|---|---|---|
| Request creation fails | The URL is malformed, relative, or uses an unsupported scheme. | Pass an absolute URL beginning with http:// or https://; apply your own host policy as well. |
| Fetch returns an error or times out | DNS, TLS, connectivity, context deadline, or client transport failure. | Check the exact error, the destination’s reachability, timeout choice, proxy configuration, and TLS setup. |
| The program reports a non-2xx status | The server returned an error, redirect-related response, authorization failure, or missing resource. | Check the URL, access requirements, server response, and redirect policy. Do not evaluate an error page as JavaScript. |
| Response exceeds the limit | The returned body is larger than the configured maximum. | Confirm that the URL returns the expected file; raise the cap only if that size is acceptable for your application. |
| Goja returns an evaluation error | The response is not JavaScript, contains invalid syntax, uses unsupported syntax, or expects missing APIs. | Inspect the response safely, verify its content type and source, then check runtime compatibility and required globals. |
Script runs but lacks window or document |
The code expects a browser environment. | Use an environment that supplies the needed browser APIs or adapt the code; Goja does not create a browser DOM automatically. |
| Script never completes | The code loops indefinitely or performs excessive computation. | Use execution interruption and stronger process/resource controls appropriate to the trust level; HTTP timeout only governs the fetch. |
Performance, reliability, and cost considerations
This design performs an HTTP request and then evaluates the downloaded source. The total latency therefore includes network, server, transfer, and execution time. Re-fetching on every operation can add latency and make behavior depend on changing remote content or availability. If the source is stable and policy permits it, consider controlled caching or distributing a pinned, reviewed copy; cache invalidation and integrity are application decisions, not Goja guarantees.
The example’s response cap limits bytes read, not the amount of CPU or memory JavaScript execution may consume. A deadline on the HTTP request does not bound evaluation. For workloads involving scripts you do not control, separate execution limits and operational isolation are essential. The Go documentation describes HTTP client behavior and configuration in net/http; Goja’s runtime and interruption mechanisms are described in its package documentation.
Or skip the browser setup
If the goal is to capture a screenshot of a website URL rather than fetch and execute JavaScript inside a Go process, ScreenshotNeo is a separate screenshot API and MCP server. It does not replace the Go-plus-JavaScript-runtime method above. A single GET request can return a PNG, JPEG, WebP, or PDF; see the ScreenshotNeo API documentation.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutecurl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Before capture, it can accept cookie or consent banners and remove 60-plus known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
Frequently Asked Questions
Does Go’s standard library execute JavaScript?
No. The standard library provides HTTP functionality for fetching the response; use a JavaScript runtime such as Goja to evaluate source.
Can Goja run a script that imports Node packages?
Not automatically. Verify the globals and module behavior the script requires and choose or supply a compatible host environment.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools

