Way to dynamically link to js scripts from client-side js? - javascript

Is there a way to dynamically link javascript pages based on client-side javascript logic? For example in client-side html code I want something like:
<script>
if(photoUpdate){
import "./phtoLoader.js" //Something like this?
}
</script>
I am currently using server side to supply dynamic script imports and it feels very inefficient.

You can create a dynamic script element and append to your document body.
function loadJS(file) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = file;
document.body.appendChild(jsElm);
}

Related

Building an External JavaScript Reference Using a local script in HTML

I have around 45-50 unique javascripts that contain data to be used in a graph. I do not want to link every single one of them. Is there a way to create a single external reference tag and fill it with a string i create in the local java inside the HTML? That way it can update at my leisure and I don't have to external reference 50 unique scripts at any given time. Note this is not on a server strictly local only for now. Also, I have only been using javascript and HTML a couple of weeks so I am a novice.
I have tried to create a tag inside the script link such as:
<script id="builtstringreference"></script>
but it produces nothing.
I have built the string that references the external javascript but can not get it back to the external reference link.
What I have in HTML:
<script id="trial"></script>
What I have in local Javascript:
var txt1 = document.getElementById("Product").value;
var txt2 = document.getElementById("Reactor").value;
var trialchange = "../Lot Data Trial Folder/lotdata_"+txt1+"_"+txt2+".js"
document.getElementById("trial").innerHTML=trialchange;
window.alert(trialchange); //just for testing
window.alert(typeof(trialchange)); //just for testing
What I want it to look like after update:
<script src="an external j.s"></script>
That way the external j.s can be changed and updated at any time without preloading 50 external j.s
I expect that I can change the external file at any time by selecting new product combos from drop-down lists which update ```txt1 and txt2 which builds the new external reference string but I feel like it's not this easy.
use something like build and then destroy the script tag
function createjs(){
var script = document.createElement('script');
script.addEventListener('load', function(){ resolve(); });
script.id = 'id-scr1';
script.type = 'text/javascript';
script.src='assets/script.js'
document.head.appendChild(script);
}
createjs();
function removeJS(id){
document.getElementById( id ).remove();
}
removeJS('id-scr1');

Js is not loading 2 times, in Angular2

I have already mention my js file path in angular.cli, it was loading only one time when angular app was initilizing and when we get back to the component then it was not loading so please give me some suggestion over this.
Thanks for your help in advance.:)
This imay help for you.
Please try to mention it on Index.html. or load script dynamatically on component.
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}

Access Google App Functions in jquery/javascript

I am using google app scripts on google sites. I have created a navigation menu, and I embedded it into the page. I want to get the pageURL() from google scripts and retrieve it in my JavaScript page. I tried using the scriptlet to get the value, but it doesn't execute. Here is what I have so far. How can I get access to values in google app scripts and use them in my JavaScript function?
google script (.gs)
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
javascript file
var pageName = <?!= getPageName()?>; // doesnt execute, need to get page url
if(pageName == linkName){
// add class here.
}
Since google loads the apps script as an iframe, I tried doing window.location.href, but it doesn't work either. The page name ends up being the name of the google app instead.
An alternative to using scriptlets is to use google.script.run (Client-side API)
It's pretty easy to use. In your case, it should be like this
code.gs
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
Javascript File:
function onSuccess(receviedPageName)
{
if(receviedPageName== linkName)
{
// add class here.
}
}//onSuccess
google.script.run.withSuccessHandler(onSuccess).getPageName();
withSuccessHandler(function) is executed if the server-side function returns successfully or withFailureHandler(function) is executed if a server side function fails to complete the task it was assigned.
Give it a try :)

.NET in js include file

Can I get print data in my .js files before sending them to the client? I want to be able to print the session id into a variable to use in getting around the flash cookie bug. Here's my code:
//Add our custom post-params
var auth = "<% = If(Request.Cookies(FormsAuthentication.FormsCookieName) Is Nothing, String.Empty, Request.Cookies(FormsAuthentication.FormsCookieName).Value) %>";
var ASPSESSID = "<%= Session.SessionID %>";
this.setPostParams({
ASPSESSID: ASPSESSID,
AUTHID: auth
});
That shows up exactly the same way in my js file. I want the server to process the code!
You can not include the .NET markup in the js file. You can use an ashx file to generate a dynamic script files if you really want to do it.
Why write it in the JS file? Write it to the page with ClientScriptManager.RegisterClientScriptBlock so the JavaScript can be cached properly. The script will still be able to access the variable in the page as long as the included script appears after the code.
I think you want to use immediate if. Like:
var auth = "<% = iif(Request...

Creating consistent URLs in jQuery

I am creating a webapp and I have been using tag in my JSPs to ensure that all my links (both to pages and to resources such as images/css) are always consistent from the root of the application, and not relative to my current location.
Some of the content I am creating using jQuery, for example, I am creating a HTML table by parsing a JSON object and using jquery.append() to insert it in to a div.
My question is, if I want to dynamically create a link using jquery how can I achieve a consistent URL regardless of the page being executed? I have tried just building the html with the tag in it, but no joy.
Thanks!
var baseURL = "/* Server-side JSP code that sets the base URL */";
$("<a />", { href: baseURL+"/my/resource/here.jsp" }); //Your proper link
Or you could do:
var baseURL = "http://"+location.host+"/my/base/url/";
//Which gives you something like http://mySite.com/my/base/url/
Get the root value of your webapp into a string using a jsp tag inside your javascript.
var root = < %=myRootVariable%> //This evaluates to http://www.myapp.com
var dynamicBit = "/foo/bar"
var dynamicLinkUrl = root + dynamicBit
var $newa = $("Hello, world");
$someJQElement.append($newa)
Hopefully none of this will occur in the global namespace. Just sayin'

Categories