how to add this html code into the append code - javascript

So I have the following html code:
<div>
<script type="text/javascript" src="https://app.ecwid.com/script.js?4549118"></script>
<script type="text/javascript"> xMinicart("style=","layout=Mini"); </script>
</div>
Please take a look at the actual code run in the browser. It shows a link.
I want to add the link to an navigation bar with the following code:
<script>
window.onload=function(){
$('nav ul').append('<li><a onClick="test()" href="javascript:void(0);">Link 3</a></li>');
}
</script>
But I'm not managing to add the code within the append correctly. How do I reference the js source and call the xMinicart function within the append code?
Thanks a lot!
super important update!
It's almost there! the following javascript code does work in jsfiddle but it doesn't work in squarespace. I'm not sure why.
$('nav ul').append('<li id="hello">test</li>');
$.getScript("https://app.ecwid.com/script.js?4549118", function(){
xMinicart("style=","layout=Mini","id=hello");
});
You can see it working here: http://jsfiddle.net/u3NKD/8/

I think you want to use jQuery's getScript function
https://api.jquery.com/jQuery.getScript/
So you would load the URL and then use the callback to execute the code
<script>
var url = "https://app.ecwid.com/script.js?4549118";
$.getScript( url, function() {
var s = document.createElement('script');
s.innerText = 'xMinicart("style=","layout=Mini");'
$('nav ul').append(s);
});
</script>

Try this instead of my other answer, here's a JSFiddle I tried
http://jsfiddle.net/W2pQA/1
<script>
$(function(){
$('ul').append('<li><a onClick="test()" href="javascript:void(0);">Link 3</a></li>');
var url = "https://app.ecwid.com/script.js?4549118";
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
var s = document.createElement('script');
s.innerText = 'xMinicart("style=","layout=Mini");'
$('ul').append(script).append(s);
});
</script>

It may be that the JS you're trying to execute is trying to run before the external JS file has completed loading.
I modified your latest JSFiddle to wait for the external file to load, then when finished, execute the xMiniCart code:
http://jsfiddle.net/u3NKD/9/
$('nav ul').append('<li id="hello">test</li>');
var script = $.getScript("https://app.ecwid.com/script.js?4549118");
$.when(script).then(function(){
xMinicart("style=","layout=Mini","id=hello");
});
Here's some documentation on the $.when code above:
https://api.jquery.com/jQuery.when/

Related

How do I trigger ad on button click? [duplicate]

I have 2 divs in my HTML.
<div id="div1"></div>
<div id="div2"></div>
On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".
I tried including the JS file on onclick event like below,
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js";
document.getElementsByTagName("head")[0].appendChild(script);
This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).
Is there any other way that I could proceed?
Thanks in Advance.
Using jQuery's $.getScript() function should do the job for you.
Here is a slice of sample code:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.
Your code almost works. You need to use .setAttribute. Here is my working code. I used jQuery as my script:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'jquery.min.js');
document.head.appendChild(script);
And that'll do it.
EDIT:
Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.
Are you using jQuery? If so, you can try $.getScript().
You might also want to check this answer. But basically, you can do something like this:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
An info I missed was, that the path has to be absolute.
Copy and paste this function on your code.
<script type="text/javascript">
getScript=(url)=>{
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
if(document.body == null){
document.head.appendChild(script);
}else{
document.body.appendChild(script);
}
}
</script>
And now call this function with your .js file url.
Example:getScript('https://abcapis.com/sample.js');
Info:
File should not contain DOMContentLoaded or $(document).ready() function

Incomplete HTML after Executing `document.write()`

After executing document.write(), Google Chrome shows me that the HTML codes is changed from Code A to Code B. It seems that document.write() overwrite the entire page. If yes, how to append the script tag inside head tag?
Code A : Before Executing document.write()
<!--DOCTYE html-->
<html>
<head>
<script src=".\js\main_CasCode.js"></script>
</head>
<body onload="main()">
<p>hi</p>
</body>
</html>
Code B : After Executing document.write()
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
</html>
JavaScript in File .\js\main_CasCode.js
function main() {
//console.log = function() {};
loadjQuery();
//waitjQueryLoaded_and_start();
}
function loadjQuery() {
console.log("Loading jQuery...");
var s = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>';
document.write(s); //<----Problem Here
}
That's because document.write erases and rewrites the document when the document has already finished rendering (like after onload). It only appears to append when called during the rendering of the page.
A better way to do this is to dynamically create a script element, add it to the page, and add an src which triggers the loading mechanism.
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
In other news, why are you loading jQuery dynamically when you have control of the page? Why not add it directly as a <script> on the HTML?
I don't think you want to be using document.write at all. You can use the following. Make a script element, and append it to the head element
var head = document.getElementsByTagName('head')[0]
var s = document.createElement('script')
s.src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"
head.appendChild(s)
document.write overwrites the whole DOM
You can create a function
function loadjQuery() {
console.log("Loading jQuery...");
var scrpt = document.createElement('script');
scrpt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
document.head.appendChild(scrpt);
}

How to load an external Javascript file during an "onclick" event?

I have 2 divs in my HTML.
<div id="div1"></div>
<div id="div2"></div>
On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".
I tried including the JS file on onclick event like below,
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js";
document.getElementsByTagName("head")[0].appendChild(script);
This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).
Is there any other way that I could proceed?
Thanks in Advance.
Using jQuery's $.getScript() function should do the job for you.
Here is a slice of sample code:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.
Your code almost works. You need to use .setAttribute. Here is my working code. I used jQuery as my script:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'jquery.min.js');
document.head.appendChild(script);
And that'll do it.
EDIT:
Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.
Are you using jQuery? If so, you can try $.getScript().
You might also want to check this answer. But basically, you can do something like this:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
An info I missed was, that the path has to be absolute.
Copy and paste this function on your code.
<script type="text/javascript">
getScript=(url)=>{
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
if(document.body == null){
document.head.appendChild(script);
}else{
document.body.appendChild(script);
}
}
</script>
And now call this function with your .js file url.
Example:getScript('https://abcapis.com/sample.js');
Info:
File should not contain DOMContentLoaded or $(document).ready() function

How to set a variable inside script tag

I have a page name index.php. And I have a script variable as follows at the top of the page:
<script>
var search_quarry = "some_test";
</script>
At the bottom of the same page I want to add this variable into the src attribute of a script tag:
<script src=NEED_TO_ADD_HERE></script>
This doesn't work:
<script src=search_quarry> </script>
Can anyone please tell me how to do this?
You'd need to do with DOM manipulation:
var search_query = 'some_test';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
or, as an alternative, though I'm not sure if this'd work:
<script id="fixme"></script>
<script type="text/javascript">
var search_query = 'some_test';
document.getElementById('fixme').src = search_query;
</script>
Why would you do this? Seems like a hack to make sever code work without fixing the back end
Option 1 is with document.write
<script>
document.write("<script src='" + search_quarry + "'></scr" + "ipt>");
</script>
Option 2 is to use createElement and appendChild
<script>
var scr = document.createElement("script");
scr.src = search_quarry;
document.getElementsByTagName("head")[0].appendChild(scr); //or use body with document onready
</script>
This is not possible. You cannot use a javascript variable inside the declaration tags for javascript. That is the point of the tags: everything inside them is parsed as javascript; everything outside them is not.
Here's a simple way to do what you want
window.onload=function(){
var script=document.createElement("script");
script.type="text/javascript";
script.src=search_quarry;
document.appendChild(script)
}
Although you would like to change window.onload into something else or just put the code inside at the top level, or if using jQuery:
$(document).ready(function(){
$(document).append("<script type='text/javascript' src='"+search_quarry+"'/>");
});

How to add jQuery in JS file

I have some code specific to sorting tables. Since the code is common in most pages I want to make a JS file which will have the code and all the pages using it can reference it from there.
Problem is: How do I add jQuery, and table sorter plugin into that .js file?
I tried something like this:
document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');
but this seems to not work.
What is the best way to do this?
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.3.min.js'; // Check https://jquery.com/ for the current version
document.getElementsByTagName('head')[0].appendChild(script);
If you want to include jQuery code from another JS file, this should do the trick:
I had the following in my HTML file:
<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>
I created a separate my_jquery.js file with the following:
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
$(this).hide("slow");
});
});
You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.
// Anonymous "self-invoking" function
(function() {
var startingTime = new Date().getTime();
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 20);
}
};
// Start polling...
checkReady(function($) {
$(function() {
var endingTime = new Date().getTime();
var tookTime = endingTime - startingTime;
window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");
});
});
})();
Other Option : - You can also try Require.JS which is a JS module loader.
/* Adding the script tag to the head as suggested before */
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "http://code.jquery.com/jquery-2.2.1.min.js";
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = handler;
script.onload = handler;
// Fire the loading
head.appendChild(script);
function handler(){
console.log('jquery added :)');
}
In if you want to add reference to any js file, say, from your project, you may also add it directly using reference tag, in Visual Studio IDE this is handled automatically by dragging and dropping the external file from solution explorer to current file (This works for mark up files, .js & .css files too)
/// <reference path="jquery-2.0.3.js" />
Here is the solution, that I adopted as a combination of some proposed solutions in some other forums.
This way you can reference both css files and other js files in one js file, thus making change next time only in a single place. Please let me know if you have any concerns on it.
I have done following:
I have created a js with name jQueryIncluder.js
declared and executed following code in this file
function getVirtualDirectory() {
var vDir = document.location.pathname.split('/');
return '/' + vDir[1] + '/';
}
function include_jQueryFilesToPage() {
var siteAddress = location.protocol + '//' + document.location.hostname + getVirtualDirectory();
var jqCSSFilePath = siteAddress + 'includes/jQueryCSS/ehrgreen-theme/jquery-ui-1.8.2.custom.css';
var jqCoreFilePath = siteAddress + 'includes/jquery-1.4.1.min.js';
var jqUIFilePath = siteAddress + 'includes/jquery-ui-1.8.2.custom.min.js';
var head = document.getElementsByTagName('head')[0];
// jQuery CSS jnclude
var jqCSS = 'cssIDJQ'; // you could encode the css path itself to generate id.
if (!document.getElementById(jqCSS)) {
var link = document.createElement('link');
link.id = jqCSS;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = jqCSSFilePath;
link.media = 'all';
head.appendChild(link);
}
// Core jQuery include
var jqc = "coreFileRefIDJQ";
if (!document.getElementById(jqc))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqc + '" src="' + jqCoreFilePath + '"></scr' + 'ipt>');
// jQueryUI include
var jqUI = "uiFileRefIDJQ";
if (!document.getElementById(jqUI))
document.write('<scr' + 'ipt type="text/javascript" id="' + jqUI + '" src="' + jqUIFilePath + '"></scr' + 'ipt>');
}
include_jQueryFilesToPage();
I referenced the above jQueryIncluder.js file in another js or xsl file of my .Net project as following:
<script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
I hope my effort is appreciated.
Thanks
it is not possible to import js file inside another js file
The way to use jquery inside js is
import the js in the html or whatever view page you are using inside which you are going to include the js file
view.html
<script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
<script src="<%=request.getContextPath()%>/js/default.js"></script>
default.js
$('document').ready(function() {
$('li#user').click(function() {
$(this).addClass('selectedEmp');
});
});
this will definitely work for you
The following answer was posted previously by another user, but provided no explanation so I decided to annotate what is happening.
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
Explanation
The problem is solved by creating a script element in JavaScript, and then setting the src attribute to the path of the jQuery file.
var jQueryScript = document.createElement('script');
Above we create the script element.
Next we set the src attribute to the path as explained before.
This can be set to
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
or
/your/path/to/jquery/file
In use:
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
Last, but not least, appending the new element to the document head:
document.head.appendChild(jQueryScript);
or body:
document.body.appendChild(jQueryScript);
In Use
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
setTimeout(function() {
// Add the rest of your code here, as we have to wait a moment before the document has jQuery as a part of it.
$("body").html("<h1>It Works!</h1>");
}, 1000);
Theres a plugin for jquery where you can just include the files you need into some other js file, here is the link for it http://tobiasz123.wordpress.com/2007/08/01/include-script-inclusion-jquery-plugin/.
Also this document.write line will write the script tags in the html not in your js file.
So I hope this could help you out, a little with your problem
The problem is you're using </script> within the script, which is ending the script tag. Try this:
document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></sc'+'ript>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></sc'+'ript>');
I believe what you want to do is still to incude this js file in you html dom, if so then this apporach will work.
Write your jquery code in your javascript file as you
would in your html dom
Include jquery framework before closing body tag
Include javascript file after including jqyery file
Example:
//js file
$(document).ready(function(){
alert("jquery in js file");
});
//html dom
<body>
<!--some divs content--->
<script src=/path/to/jquery.js ></script>
<script src=/path/to/js.js ></script>
</body>
If you frequently want to update your jquery file link to a new version file, across your site on many pages, at one go..
Create a javascript file (.js) and put in the below code, and map this javascript file to all the pages (instead of mapping jquery file directly on the page), so when the jquery file link is updated on this javascript file it will reflect across the site.
The below code is tested and it works good!
document.write('<');
document.write('script ');
document.write('src="');
//next line is the path to jquery file
document.write('/javascripts/jquery-1.4.1.js');
document.write('" type="text/javascript"></');
document.write('script');
document.write('>');
You can create a master page base without included js and jquery files. Put a content place holder in master page base in head section, then create a nested master page that inherits from this master page base. Now put your includes in a asp:content in nested master page, finally create a content page from this nested master page
Example:
//in master page base
<%# master language="C#" autoeventwireup="true" inherits="MasterPage" codebehind="MasterPage.master.cs" %>
<html>
<head id="Head1" runat="server">
<asp:ContentPlaceHolder runat="server" ID="cphChildHead">
<!-- Nested Master Page include Codes will sit Here -->
</asp:ContentPlaceHolder>
</head>
<body>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<!-- some code here -->
</body>
</html>
//in nested master page :
<%# master language="C#" masterpagefile="~/MasterPage.master" autoeventwireup="true"
codebehind="MasterPageLib.master.cs" inherits="sampleNameSpace" %>
<asp:Content ID="headcontent" ContentPlaceHolderID="cphChildHead" runat="server">
<!-- includes will set here a nested master page -->
<link href="../CSS/pwt-datepicker.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery-1.9.0.min.js" type="text/javascript"></script>
<!-- other includes ;) -->
</asp:Content>
<asp:Content ID="bodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ContentPlaceHolder ID="cphChildBody" runat="server" EnableViewState="true">
<!-- Content page code will sit Here -->
</asp:ContentPlaceHolder>
</asp:Content>
Dynamic adding jQuery, CSS from js file.
When we added onload function to body we can use jQuery to create page from js file.
init();
function init()
{
addJQuery();
addBodyAndOnLoadScript();
addCSS();
}
function addJQuery()
{
var head = document.getElementsByTagName( 'head' )[0];
var scriptjQuery = document.createElement( 'script' );
scriptjQuery.type = 'text/javascript';
scriptjQuery.id = 'jQuery'
scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
var script = document.getElementsByTagName( 'script' )[0];
head.insertBefore(scriptjQuery, script);
}
function addBodyAndOnLoadScript()
{
var body = document.createElement('body')
body.onload =
function()
{
onloadFunction();
};
}
function addCSS()
{
var head = document.getElementsByTagName( 'head' )[0];
var linkCss = document.createElement( 'link' );
linkCss.rel = 'stylesheet';
linkCss.href = 'E:/Temporary_files/temp_css.css';
head.appendChild( linkCss );
}
function onloadFunction()
{
var body = $( 'body' );
body.append('<strong>Hello world</strong>');
}
html
{
background-color: #f5f5dc;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temp Study HTML Page</title>
<script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>
</head>
<body></body>
</html>
If document.write('<\script ...') isn't working, try document.createElement('script')...
Other than that, you should be worried about the type of website you're making - do you really think its a good idea to include .js files from .js files?
just copy the code from the two files into your file at the top.
or use something like this http://code.google.com/p/minify/ to combine your files dynamically.
Josh
I find that the best way is to use this...
**<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>**
This is from the Codecademy 'Make an Interactive Website' project.
After lots of research, I solve this issue with hint from ofir_aghai answer about script load event.
Basically we need to use $ for jQuery code, but we can't use it till jQuery is loaded. I used document.createElement() to add a script for jQuery, but the issue is that it takes time to load while the next statement in JavaScript using $ fails. So, I used the below solution.
myscript.js is having code which uses jQuery
main.js is used to load both jquery.min.js and myscript.js files making sure that jQuery is loaded.
main.js code
window.load = loadJQueryFile();
var heads = document.getElementsByTagName('head');
function loadJQueryFile(){
var jqueryScript=document.createElement('script');
jqueryScript.setAttribute("type","text/javascript");
jqueryScript.setAttribute("src", "/js/jquery.min.js");
jqueryScript.onreadystatechange = handler;
jqueryScript.onload = handler;
heads[0].appendChild(jqueryScript);
}
function handler(){
var myScriptFile=document.createElement('script');
myScriptFile.setAttribute("type","text/javascript");
myScriptFile.setAttribute("src", "myscript.js");
heads[0].appendChild(myScriptFile);
}
This way it worked. Using loadJQueryFile() from myscript.js didn't work. It immediately goes to the next statement which uses $.
The latest answer is outdated, try this:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.1.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
Why are you using Javascript to write the script tags? Simply add the script tags to your head section. So your document will look something like this:
<html>
<head>
<!-- Whatever you want here -->
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script src="/javascripts/jquery.tablesorter.js" type="text/javascript"></script>
</head>
<body>
The contents of the page.
</body>
</html>

Categories