Skip to content
CodeLifter
Search/ Browse prompts
CodeLifter Forum

How do you modernise an old cut-and-paste JavaScript script?

Staff answerWritten by CodeLifter editors · Script Shelf1 replyupdated

Short answer

Should you convert an old script into a JavaScript module? Only if you want its benefits and accept two side effects. You load a module with <script type="module" src="..."> . MDN's modules guide says modules "use strict mode automatically" and "are deferred automatically", so you get steps 2 and 6 of the opening post for free.

From the top reply by CodeLifter editors ·
CiteCodeLifter Forum, "How do you modernise an old cut-and-paste JavaScript script?", https://codelifter.com/forum/posts/how-do-you-modernise-an-old-cut-and-paste-javascript-script/, accessed 2026-11-29.
  1. Staff, CodeLifter ·

    To modernise an old cut-and-paste JavaScript script, move it into its own file loaded with defer, replace inline onclick and onload attributes with addEventListener, swap var for const or let, replace document.write() and string HTML with DOM methods, and turn on strict mode. Then test it with the keyboard and the console open.

    Is it worth modernising, or should you replace it?

    Decide that first, because the work differs. If the browser now does the job itself (an email checker, a favicon script, a scrollbar colour), replace the script with the HTML or CSS feature. If the job was the problem (popups on load, right-click blocking, resizing the window), delete it. The thread on whether old scripts still work has a table of those cases and a ten-minute test. Modernise only what is left: short scripts that still do something useful, such as a quote rotator or a slideshow.

    What does a typical old script look like?

    Here is a small example written for this answer, in the style of early tutorial sites:

    <body onload="showQuote()">
    <div id="quote"></div>
    <script language="JavaScript">
    var quotes = new Array("Measure twice.", "Ship small.", "Read the error.");
    function showQuote() {
      var i = Math.floor(Math.random() * quotes.length);
      document.getElementById("quote").innerHTML = "<p>" + quotes[i] + "</p>";
    }
    </script>
    

    It works, but it mixes markup and code, puts quotes and showQuote on the global object where any other script can overwrite them, writes HTML from a string, and relies on an attribute on <body> that only one script can own.

    The steps, in order

    1. Copy it into your own file. Save the code as, say, js/quote.js, and note where it came from and under what terms; the thread on pasting scripts from old tutorial sites covers the licence and provenance side.
    2. Load it with defer. Replace the inline block with <script src="/js/quote.js" defer></script> in the <head>. MDN's script element reference says defer makes the script run "after the document has been parsed, but before firing DOMContentLoaded", and that deferred scripts run in the order they appear. The elements your script looks up already exist when it runs, so <body onload> is no longer needed. The language attribute can go too; MDN lists it as deprecated, with values that "were never standardized."
    3. Replace inline handlers. Remove onclick="...", onmouseover="..." and onload="..." from the markup and attach the same code with addEventListener. MDN's addEventListener page calls it "the recommended way to register an event listener" and lists the main benefit for pasted code: "It allows adding more than one handler for an event", so two scripts no longer fight over one attribute.
    4. Swap var for const or let. Use const for anything never reassigned and let for the rest. MDN's let reference notes that let declarations "do not create properties on globalThis" at the top level of a script, so they stop leaking into the global object.
    5. Stop building HTML from strings. Replace innerHTML = "<p>" + text + "</p>" and any document.write() with textContent, document.createElement() and append(). MDN's append() page says strings passed to it "are inserted as equivalent Text nodes", so text stays text. The innerHTML thread explains why this matters.
    6. Turn on strict mode. Add "use strict"; as the first line of the file. MDN's strict mode page says it "makes it impossible to accidentally create global variables": a mistyped name in an assignment now throws an error instead of quietly creating a new global.
    7. Replace browser checks with feature checks. Delete any branch on the browser's name and test for the method you need instead. MDN's feature detection guide calls browser sniffing "a terrible practice that should be discouraged at all costs."
    8. Test with the keyboard and the console open. Tab to every control, press Enter and Space, and read every console warning.
    Eight numbered steps for modernising an old cut-and-paste JavaScript script
    The eight modernising steps in the order this article gives them

    The same script, modernised

    <div id="quote"></div>
    <script src="/js/quote.js" defer></script>
    
    "use strict";
    
    const quotes = ["Measure twice.", "Ship small.", "Read the error."];
    const target = document.getElementById("quote");
    
    if (target) {
      const p = document.createElement("p");
      p.textContent = quotes[Math.floor(Math.random() * quotes.length)];
      target.append(p);
    }
    

    The if (target) check matters. MDN's getElementById page says it returns null when no element has that id, and the id is case-sensitive, so a page without the box no longer throws an error.

    Old pattern, modern replacement

    Old pattern Replace with Why
    <body onload="init()"> defer on the script tag Elements exist when the script runs; no attribute to share
    onclick="doThing()" in markup el.addEventListener("click", doThing) Several handlers can coexist; markup stays markup
    var at top level const or let No properties added to the global object
    innerHTML or document.write() with text textContent, createElement, append Text is never parsed as HTML
    if (navigator.appName == ...) if ("showModal" in dialog) style checks Tests what you need, not who the browser claims to be
    <script language="JavaScript"> <script src="..." defer> language is deprecated; code lives in its own file

    Can you ask an assistant to do it?

    Yes, but ask for the specific changes, not "modernise this", or you may get a framework added. Name the steps above in the prompt, ask it to keep behaviour identical, and diff the result against the original. How to write a coding prompt explains why listing constraints works better than naming a style. For the classic jobs, the Script Shelf and the random quote generator prompt already have reviewed rewrites.

    Short version

    • First decide whether to modernise, replace with the platform, or delete.
    • Move the code into its own file loaded with defer, and drop onload and inline handlers.
    • Use const and let, DOM methods instead of HTML strings, and "use strict";.
    • Check for missing elements and features instead of browser names.
    • Test with the keyboard and read every console warning.
    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. CodeLifter editorsStaffStaff, CodeLifter ·

    Should you convert an old script into a JavaScript module? Only if you want its benefits and accept two side effects. You load a module with <script type="module" src="...">. MDN's modules guide says modules "use strict mode automatically" and "are deferred automatically", so you get steps 2 and 6 of the opening post for free.

    The first side effect is scope. The same guide says module features "aren't available in the global scope." Any inline handler left in the markup, such as onclick="showQuote()", will then fail with a ReferenceError, because showQuote is no longer a global. Finish step 3, replacing every inline handler with addEventListener, before you switch.

    The second is local testing. MDN warns that loading the page from a file:// URL makes you "run into CORS errors due to JavaScript module security requirements", so test through a local server instead, for example python3 -m http.server 8000 --bind 127.0.0.1. For a single short snippet with no imports, a classic script with defer and "use strict"; is enough. Modules pay off once you split code across files and use import and export.

CodeLifter Forum. Questions and answers on vibe coding prompts, AI-generated code provenance, project AI policies and MCP tools.