Is there any way to load a local JS file dynamically?

后端 未结 4 1245
一整个雨季
一整个雨季 2020-12-03 05:45

For development purposes, I\'d like to be able to easily load locally-stored scripts into the browser instead of having to copy-paste to the console.

Creating a new

相关标签:
4条回答
  • 2020-12-03 06:23

    In Chrome, you can create an extension that holds all of the local files that you need to load. It will make your files accessible via chrome-extension://... instead of file://...

    Make a file named manifest.json in a new folder and fill it with:

    {
      "name": "File holder",
      "manifest_version": 2,
      "version": "1.0",
      "web_accessible_resources": ["test.js", "other.js", "yetanother.js"]
    }
    

    Then, put all the scripts you want to load in that new directory, and make sure they are included in the web_accessbile_reources manifest list. Load the extension by going to chrome://extensions, enabling Developer Mode, and selecting the new folder with Load unpacked extension....

    Now you can access all the files in your extension directory using chrome-extension://[app_id]/[file_name], where "app_id" is the hash listed for the extension on the chrome://extensions page. Note that because the protocols and hostnames differ from where you've doing your actual work (unless you decide to do all your development in the extension folder, which might be acceptable to you), the extension resources are cross-domain and can only be loaded via <script> tag.

    Now from the console, you can do:

    var s = document.createElement("script");
    s.src = "chrome-extension://aefigdoelbemgaedgkcjpcnilbgagpcn/test.js";
    document.body.appendChild(s);
    

    (Assuming your file is test.js and your app id is aefigdoelbemgaedgkcjpcnilbgagpcn.)

    It's a quite bit to type, I know, but perhaps you can store the chrome-extension://[app_id] part as a shorthand variable?

    0 讨论(0)
  • 2020-12-03 06:30

    Sadly, Chrome doesn't allow you to load local files via AJAX; however, you can work around this limitation by launching the browser with the flag --disable-web-security (details vary per host operating system).

    0 讨论(0)
  • 2020-12-03 06:30

    Have you tried a relative path from your page to your js file liek so...

    src='/js/javascript.js'

    0 讨论(0)
  • 2020-12-03 06:32

    you need to run local http server

    this is a good document for this:

    https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server

    0 讨论(0)
提交回复
热议问题