Adding external Javascript file based on url string - javascript

I am attempting to load an external JS file to the end of the body if the URL does not container a given parameter. Here is what I have tried without any success. I am looking to load the file if the URL does not contain ?A=Edit
if (/[?]A=Edit/.test(window.location.href)) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/inner-functions.js';
$('body').append(script);
}
If anyone can point me in the right direction that would be great.

Just inverse your condition:
if (!/[?]A=Edit/.test(window.location.href)) {
...

You should verify your application context/state inside your .js file, not outside.

Related

Link external pure javascript file to my React component

I am trying to build a react component with happy birthday animation written in an external javascript file. I know that we could link external javascript file by:
componentDidMount() {
const script = document.createElement("script");
script.async = true;
script.src = "./hbd.js";
script.type = "text/javascript";
this.div.appendChild(script);
}
In the hbd.js javascript file I have a function anim() which I could call to display an animation.
However, if I don't change the type of script to script.type = "text/bable " or script.type = "text/jsx " it gives me an Uncaught SyntaxError: Unexpected token '<'
error. If I do change the types, no error is given but the file simply won't load, and no animation effect is seen.
Does someone out there know if it is possible at all to do that with React?
Make sure that you can GET the JavaScript file hbd.js. Point your browser to the full url and make sure that the hbd.js file is returned by the web server. If you have your web server locally, it would be something like http://localhost/hbd.js.

How to include dynamic Javascript file in the DOM without repeating same file

I want to load <div> content dynamically by using AJAX in a specific div. After the AJAX call I want to load a JS file in the footer. I loaded content by clicking menu without page loading by using URL hash. My problem is when I click the same link multiple times, the JS file is loading multiple times because the JS file is appended. That's why every event occurs multiple times. I want to load the JS file before checking if the file is already loaded into the DOM. If the file is not loaded in the DOM, I will append a JS file in the DOM.
As the answer suggested by this URL, here is my code:
var Utils = {
loadjs: function(url){
var footer = document.getElementsByTagName('body')[0];
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
footer.appendChild(script);
},
}
Utils.loadjs(url);
You can read the script tags to search for a particular script is there or not. Something like below:
var Utils = {
loadjs: function(url) {
var me = document.querySelectorAll('script[src="' + url + '"]');
if (me && me.length >= 1) {
return null;
}
var footer = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
footer.appendChild(script);
},
}
Utils.loadjs(url);
You can use dynamic import() syntax to load modules, even from regular scripts.
This has the benefit of loading those scripts as modules, which are always in strict mode and have module scope.
Read more about dynamic import
So, instead of Utils.loadjs(url), just import(url)

problems when creating a script tag to a local file in android webview

I have an Android application that consist in a simple WebView that load a local html file in the assets folder of the project.
The HTML has a tag that calls (AJAX) an external service and expects as a response a String that represent a .js filename (say, 'test.js').
In test.js there is a simple funcion declaration, as:
var testFunction = function(){
// some code here
}
The AJAX callback then construct via javascript a tag that points to the .js file and append it to the head of the document; then call the testFunction:
$.ajax('externalService').done(function(response){
var script = // construct the script tag;
$('head').append(script);
testFunction();
});
Important: the script tag points to an external .js file, like
<script src="http://justatest.com/test.js">
... and all works fine!
Now i try to do the same thing putting the test.js inside the assets folder of the project. Obviously i changed the src of the script created in the callback with a relative path:
<script src="test.js"></script>
but when i try to invoke the function testFunction i get an error (testFunction is not defined).
The local path is correct (i put jquery.js in the same local folder of test.js and loaded it directly in the html with a with no errors).
I put all the attributes (like type="text/javascript") in the tag as well...
so, why the webview doesn't load a local .js file in this way?
thank you :)
EDIT: I tried the solution found in this thread:
jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources
and it worked!!!!
I tried the solution found in this thread:
jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources
and it worked!
I report the solution:
var scriptUrl = "test.js";
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptUrl;
script.onload = function() { alert("Success"); };
script.onerror = function(e) { alert("failed: " + JSON.stringify(e)); };
head.appendChild(script);
So if i use the jquery append() method it doesn't work, but if i use the javascript appendChild method it work...

Can I Load CSS Using the "load.js" Library?

I recently found out about load.js, but I can't seem to find any indication of whether or not this is possible... (Note: I can't find a 'load.js' tag..)
I've got load.js successfully loading all my JS files, so I know it works. Has anyone got it working for loading CSS files as well?
Update: remyabel's solution worked perfectly for loading the physical files, but it seems there are a few quirks to this process...
For some reason, the order in which the CSS files are loaded and whether they're all done in one load(file1,file2); or in stages with load(file1).then(file2); seems to affect how the style rules are applied to the markup. I'm going to set up a few test cases on my local machine to try work out how or why this happens, but for now at least the files are being loaded.
Final Note:
Following on from the solution posted below, I've decided to use head.appendChild(script); instead of head.insertBefore(script, head.firstChild); to add the CSS elements to the DOM (still uses the original method for JS files).
This doesn't affect the order in which files are fetched and processed, but it makes Load.js insert my CSS links in the same order they were listed and at the end of the header instead of the beginning.
Direct from the source code
function asyncLoadScript(src) {
return function (onload, onerror) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
My suggestion is to modify the script (which doesn't seem to contain much) to mirror the function but for a link tag, rather than a script tag.
to reflect OP's comment
The script is built on top of chain.js so it may be more complicated than expected.
Unless you want something else, I'm pretty sure what I wrote above is what you need to change, so it would look like:
function asyncLoadScript(src) {
return function (onload, onerror) {
// Get file extension
var ext = src.split('.').pop();
if (ext == "js")
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
} else if (ext == "css")
{
var script = document.createElement('link');
script.type = 'text/css';
script.href = src;
script.rel = "stylesheet";
}
Theoretically that should work. Make another comment if it doesn't work.

Modify "src=" in <script> tags before loading--without jQuery

Basically, I want to do this:
<script src=" path + '/jquery.js'"></script>
(Obviously that won't work.)
I have a standalone page loading external scripts with <script>, but the URL needs to be prefixed with the variable path (because the page is run on different servers in different environments). I easily get path from the URL which always ends with "?path=X" where X is the actual path.
If I had jQuery, I know I could use getScript() to dynamically load external .js files, but jQuery is one of the files I need to load! I don't need anything too complicated here, no need to worry about encoding or file-types, it's a fairly simple situation except for the changing servers.
You need to use plain javascript if jquery not loaded. Something like that:
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path + '/jquery.js');
document.getElementsByTagName("head")[0].appendChild(fileref);
fileref.onload = function(){alert('loaded')};
You can load JS files by inserting them into the head with javascript, and at the same you can use your variable for the path when setting the source attribute:
<script type="text/javascript">
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = path + '/jquery.js';
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
</script>

Categories