Jones Lee
Jones Lee

Reputation: 65

Javascript: Error with dynamic <script> src value and JSON.parse

I am trying to dynamically load a selected JS file into my HTML file, of which the JS file content will be used to populate the HTML.

Currently, I have a a 3 different JS files (sampleFile.js, sampleFile2.js, sampleFile3.js) to mimic 3 JSON files. All three files contain a data const variable.

Example of sampleFile2.js

const data = '[{"name" : "jane", "age": "twenty"}, {"name": "caleb", "age": "eight"}]'

Within <script> in main.html, I want to load one of these 3 JS file as the script src value depending on the parameters in the URL.

For example, if my url ends with '?sampleFile2', my script in my main.html file will be <script type="text/javascript" src="sampleFile2.js">.

I then extract the data const variable out to populate my HTML screen, using mySample = JSON.parse(data);, but always seem to get an error at this step and nothing gets populated.

main.html
<script> appended before </body>

        <script>
            // Get the URL value and identify file
            var jsFile = location.search.substr(1) + ".js";
 
            // Create <script> in HTML header
            var loadFileScript = document.createElement('script');
            loadFileScript.type = "text/javascript";
            loadFileScript.src = "jsFile";
            document.head.appendChild(loadFileScript);

            // Extract content from sampleFile
            var mySample = JSON.parse(data);

            // Populate HTML using sampleFile contents
            populateHTML(mySample);
            
            function populateHTML(mySample) {
                // Do stuff to populate HTML here
            }
        </script>

My constraints are that I can only use HTML and Javascript. When I troubleshooted, I had no problem getting the desired <script>. However, in the JSON.parse, I keep getting an error:

Uncaught ReferenceError: data is not defined at main.html?sampleFile2.

Anybody knows how else to rectify?

Upvotes: 0

Views: 240

Answers (1)

Jones Lee
Jones Lee

Reputation: 65

Thanks to commenter @user2740650, adjusted my script codes as per www.stackoverflow.com/a/16231055/2740650, it works now!

       <script>
            // Get the URL value and identify file
            var jsFile = location.search.substr(1) + ".js";
 
            // Create <script> in HTML header
            var loadFileScript = document.createElement('script');
            loadFileScript.type = "text/javascript";
            document.head.appendChild(loadFileScript);

            // Use function on load
            loadFileScript.onload = function() {
                var mySample = JSON.parse(data);
                populateHTML(mySample);
            };

            loadFileScript.src = jsFile;
            
            function populateHTML(mySample) {
                // Do stuff to populate HTML here
            }
        </script>

Upvotes: 1

Related Questions