Providing inputs to a JavaScript function, yet the function fails to execute properly

My JavaScript code detects the useragent for Android, iPhone, or iPod and loads specific JavaScript files accordingly. The code functions perfectly, but I noticed that having two 'createScript' functions with different names performing the same task is redundant. Therefore, I attempted to use a parameter/variable instead, but without success.

<script type="text/javascript">
    if(navigator.userAgent.match(/Android/i) ||
     navigator.userAgent.match(/webOS/i) ||
     navigator.userAgent.match(/iPhone/i) ||
     navigator.userAgent.match(/iPod/i)) {
        function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
                window.onload = func;
            } else {
             window.onload = function() {
                if (oldonload) {
                oldonload();
                }
                func();
                }
        }
        }

function createScript(scriptname) 
{ 
var oNode=document.createElement("script"); 
document.getElementsByTagName("body")[0].appendChild(oNode);

oNode.setAttribute("id", "newScript", 0); 
oNode.setAttribute("type", "text/javascript", 0); 
oNode.setAttribute("src", scriptname, 0); 
} 

createscriptlibrary = createScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js");
createmyscript = createScript("nav.js");

addLoadEvent(createscriptlibrary);
addLoadEvent(createmyscript);
}
</script>

I've been attempting to modify the code above by using parameters in the 'createScript' function, but it's not functioning as intended:

<script type="text/javascript">
if(navigator.userAgent.match(/Android/i) ||
 navigator.userAgent.match(/webOS/i) ||
 navigator.userAgent.match(/iPhone/i) ||
 navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
         window.onload = function() {
            if (oldonload) {
            oldonload();
            }
            func();
            }
    }
    }


function createScript(scriptname) 
{ 
var oNode=document.createElement("script"); 
document.getElementsByTagName("body")[0].appendChild(oNode);

oNode.setAttribute("id", "newScript", 0); 
oNode.setAttribute("type", "text/javascript", 0); 
oNode.setAttribute("src", + scriptname + , 0); 
} 

createscriptlibrary = createScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js");
createmyscript = createScript("nav.js");

addLoadEvent(createscriptlibrary);
addLoadEvent(createmyscript);
}
</script>

If possible, could someone assist me in resolving this issue? Thank you.

Answer №1

The reason why that approach is ineffective is because the function createScript does not return a function as expected.

A straightforward solution would be to implement it like this:

addLoadEvent(function() { createscript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"); });
addLoadEvent(function() { createScript("nav.js"); });

It's important to note that assigning the same value for the id attribute in each script tag created by createScript is not allowed.

If you are in an ES5-supported environment, you could utilize Function#bind, but based on your question, it seems that relying on such an environment may not be feasible. Nevertheless, here is how you could do it:

addLoadEvent(createscript.bind(undefined, "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"));
addLoadEvent(createScript.bind(undefined, "nav.js"));

Alternatively, utilizing libraries like RequireJS would be a much simpler and efficient solution. :-)


By the way, your createScript function could be more concise (and the one mentioned in your query has a syntax error with the + before scriptName):

function createScript(scriptName) {
    var oNode = document.createElement('script');
    oNode.src = scriptName;
    document.body.appendChild(oNode);
}

No need to specify the type, and avoid setting the id unless each script has a corresponding identifier. Both src and type properties directly reflect, eliminating the necessity of using setAttribute.


Lastly, remember that your nav.js cannot assume jQuery is already loaded when scripts are loaded dynamically. Even if you prioritize adding the jQuery script first, dynamically added scripts might not be executed sequentially. Hence, include a safeguard in your nav.js code like this:

(function() {
    check();

    function check() {
        if (typeof jQuery === "undefined") {
            setTimeout(check, 50);
        }
        else {
            init();
        }
    }

    function init() {
    }
})();

This will verify the presence of jQuery and delay by 50ms if not found (you may want to set a timeout limit).

Answer №2

I recently made an update where I needed to dynamically add a CSS file. Instead of my original approach, I used the code below and it worked perfectly. Thank you!

<script type="text/javascript">
var headID = document.getElementsByTagName("head")[0];         
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = 'jqueryjava.css';
headID.appendChild(cssNode);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery - Creating an organized hierarchy list

My website's DOM structure is shown below: <ul> <li id="Browse"> Browse <ul id="browse-one"> </ul> </li> </ul> At the bottom of the page, my jQuery script looks like this: $("#Brow ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

Learn the process of marking an option as selected within an Angular component

I have an Angular component that displays a question along with a dropdown menu (<select>) to choose from various answers. My goal is to programmatically set one of the options as selected based on certain parameters present in the application' ...

innovative jquery table creator

I have created a basic dynamic HTML table generator using jQuery, see below... <button id="addcolumn">Add Column</button> <button id="addrow">Add Row</button> <table width="100%" border="1" cellpadding="0" cellspacing="0"> ...

Issues encountered with the functionality of face-api and tensorflow.js within the browser

I've been trying to execute this example in the browser Check out the example here Specifically looking at this code snippet <!DOCTYPE html> <html> ... (Contents of the code snippet) ... </body> </html> Unfortunately, I&apos ...

Missing Component when Nested within Route in React Router v6

While incorporating the ChoosePlayer component within a Route using React Router v6, <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/players"> <Route element ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

Fetching basic information from an API using Ember.js

I am facing an issue with my Ember.js page where I am trying to retrieve data from a REST API. The API is provided by apiary.io and it returns a simple set of data as shown below: {"semantics": [ {key : "11111", name : "Block 1"}, {key : "22222", name ...

Automatically storing modified text from richtextbox into the database for safekeeping

I have developed a basic note-taking application using jquery and php. Currently, when the user clicks the save button, it sends an ajax request with all the data to update it in the mysql database. Everything is functioning correctly. However, I now want ...

Jquery's remove function fails to function correctly when used on a cloned element

I am facing an issue where I have a list of rows that need to be deleted. However, when I attempted to use jQuery's remove function, it only removed the original row and not its clone. My goal is for the parent element of the parent to be removed when ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Exploring the power of promise chaining within AWS Lambda

I'm feeling a bit confused about how Promise chaining works in AWS Lambda. exports.handler = async(event) => { firstMethod = () => { return new Promise(function(resolve, reject){ setTimeout(function() { ...

Struggling with the alignment of divs in a vertical manner

Looking for a way to align multiple divs inside another div vertically with even spacing between them? They should all start at the top. Currently, my solution has the child-divs positioned at the top-left corner of the parent div (see the first picture): ...

What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescrip ...

The webpage appears to be stuck and unresponsive to scrolling

Currently in the process of developing a website, I've integrated stellar.js for parallax effects and niceScroll.js to ensure smooth scrolling. However, I'm facing an issue where I am unable to scroll both horizontally and vertically. To address ...

The spacing between elements in Flexbox is too excessive, creating an overly wide gap

How can I maintain a fixed 40 pixel gap between columns in flexbox without it increasing as the screen width widens? (I apologize for the brevity of this description, but there are no additional details to provide at this time) .browser-box { max-wid ...

Utilize Rails file_field input as a clickable button

Currently, I have a button that needs to trigger the action associated with a file_field in my Rails application. Below is the erb code I am using: <label for='file-input'> <span class='btn btn-success' style='max-width ...

Encountering an error while configuring app.js with git bash

I am just starting out and eager to learn from scratch. I am trying to configure app.js in my sp-node-mysql folder to interact with MySQL using JavaScript. However, I seem to be stuck. Here is the code line in question: var mysql = require("mysql"); and ...

Columns that can be resized in a right-to-left (

Whenever I use RTL, the columns behave erratically when resizing... I have implemented colResizable. You can see an example here: http://jsfiddle.net/r0rfrhb7/ $("#nonFixedSample").colResizable({ fixed: false, liveDrag: true, gripInnerHtml: "<d ...

Tried utilizing express to log URL parameters, but to no avail as it did not show any output on the console

Whenever I enter /posts/whatever at the end of the root URL, it doesn't log what comes after /posts to the console. app.get("/posts/:userId", function(req, res) { console.log(req.params.userId); }); Update: Here's the complete code: ...