I'm using Lightbox but i only want the references to the stylesheet and javascript files to be in the masterpage header on one page on the site (the page that uses lightbox). how do I programmatically add references to the stylesheet and javascript files in the page load?
the stylesheet is the 'css' folder and the three javascript files are a 'js' folder
try...
Page.ClientScript.RegisterClientScriptInclude("JScripts", ResolveUrl("~/js/JScripts.js"));
Add two placeholders ("JsPlaceholder" and "CSSPlaceholder") to your header on master page and call those methods:
public void AddJavascriptFile(string path)
{
PlaceHolder p = (PlaceHolder)Page.Header.FindControl("JsPlaceholder");
p.Controls.Add(new LiteralControl(string.Concat("<script type='text/javascript' src='", path, "'></script>\n")));
}
public void AddCssFile(string urlPath)
{
HtmlLink cssLink = new HtmlLink();
cssLink.Href = path;
cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");
PlaceHolder p = (PlaceHolder)Page.Header.FindControl("CssPlaceholder");
p.Controls.Add(cssLink);
}
Try (in C# but you should get the idea):
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HtmlLink cssLink = new HtmlLink();
//Create and configure the CSS link.
cssLink.Attributes.Add("rel", "Stylesheet");
cssLink.Attributes.Add("type", "text/css");
cssLink.Href = "~/Path/To/File.css";
//Add the CSS link to the page header.
this.Header.Controls.Add(cssLink);
//Add a script include to the page's ClientScript.
this.ClientScript.RegisterClientScriptInclude("NameOfScript", this.ResolveUrl("~/Path/To/File.js"));
}
you can do it like this
added this to your header:
<asp:placeholder runat="server" id="lightbox" visible="false">
<link rel="stylesheet" href="/css/style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"</script>
</asp:placeholder>
and from your codebehind set
lightbox.visible=true;
You should also note that normally you want to keep as much html on the page instead of having it in your codebehind so it will be easy for the designer to make changes
Related
I develop an application that use a WebView in a WinForm using VB.NET.
The HTML code displayed in WebView is dynamically generated using VB.NET code.
wvSelect.Settings.IsScriptNotifyAllowed = True
wvSelect.Settings.IsJavaScriptEnabled = True
wvSelect.NavigateToString(sHtmlText)
where sHtmlText contains HTML tags and values.
This work well.
My HTML string is generated in a module
Public eHtml =
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
// script (see code below)
</script>
<style type="text/css">
That's working, but Javascript code crash every time I write a < characters and color formatting of Javascript code is not optimal.
I know that I can use
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
That works for < and > characters but color formatting is very bad.
So, I have decided to move all my Javascript code in .JS file.
My HTML now, look like this
Public eHtml =
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="file:///D:/Documents/app.js"></script>
<style type="text/css">
Since, I have made this change, what is displayed in WebView is different from what I obtained before !
I suppose that .JS file is not called, not found or something else.
You must know that just before loading HTML string in WebView, I save it in an .HTML file.
When I double click on this .HTML file, Chrome load it and what is displayed is correct.
The problem happens only when HTML string is displayed on WebView.
As you can see, I don't have any problem importing JQuery script.
This problem is only for LOCAL scripts.
For information, my Javascript file contains following lines (I have removed some lines)
It is just to show that JQuery is used.
var eUnicode;
var iCounter = 0;
var eDraggable;
$(document).ready(function () {
$('.button').attr('draggable', 'True');
$('.digit').click(function (ev) { clickDigit(ev); });
$(".button").click(function (ev) {
clickButton(ev.target);
});
showFirstTab();
});
function clickButton(eButton) {
var sName = event.srcElement.innerText;
hideAllOnglets();
eButton.style.background = "orange";
showOnglet(sName);
}
function showTab(sName) {
var eOnglet = document.getElementById(sName);
eOnglet.style.display = "block";
}
Has somebody already encountered and resolved this problem ?
I have solved my problem using an embedded file (VB.Net Resource).
This technic is more safe because embedded file in not modifiable by user on installation location.
The Javascript.js file is located my application file/folder tree and has been defined as embedded resource in Build Action property as explained on How do I include a .jpg into a dll?
.
I don't use <script src='location'> tag because it don't work and also because HTML string is already dynamically build from my code for other part.
My VB.Net code is following
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
sHtmlText = eHtml.ToString()
sHtmlText = sHtmlText.Replace("(%-ONGLET-%)", sOngletText)
sHtmlText = sHtmlText.Replace("(%-TABLE-%)", sTableText)
reader = New StreamReader(ass.GetManifestResourceStream("UnicodeInput.JavaScript.js"))
Dim sScriptText = reader.ReadToEnd()
reader.Close()
sHtmlText = sHtmlText.Replace("(%-SCRIPT-%)", sScriptText)
reader = New StreamReader(ass.GetManifestResourceStream("UnicodeInput.StyleSheet.css"))
Dim sStyleText = reader.ReadToEnd()
reader.Close()
sHtmlText = sHtmlText.Replace("(%-STYLE-%)", sStyleText)
wvSelect.Settings.IsScriptNotifyAllowed = True
wvSelect.Settings.IsJavaScriptEnabled = True
wvSelect.NavigateToString(sHtmlText)
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("output.html", False)
file.Write(sHtmlText)
file.Close()
As you can see I have done same improvement for CSS file and I have discovered that this file has some errors !
My 'pseudo' HTML code is following
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!--
<script type="text/javascript" src="./app.js"></script>
<script type="text/javascript" src="file:///D:/Documents/+Informatique/Application/#Visual Basic.NET/UnicodeInput/app.js"></script>
<script src="file:///D:/Documents/app.js"></script>
-->
<script type="text/javascript">
(%-SCRIPT-%)
</script>
<style type="text/css">
(%-STYLE-%)
</style>
</head>
<body>
<div id="onglet">
<div class='button'>Keyboard</div>
(%-ONGLET-%)
<div class='button' onclick="GetNewCmdFile()">*ADD</div>
</div>
What is in comment is what I have already tried that doesn't work in WinForm VB.Net WebView but works perfectly in pure HTML on Chrome.
I want to remove mentioning scripts every page like
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js"></script>
it should be mentioned at once.like a common place to refer for source.
i have my framework in 3.5. how can i achieve this.
create a new project to hold all JavaScript files that you need want throughout the application. You can embed all the script into the DLL. That way, if the DLL is deployed to the website, all JavaScript files are also automatically deployed.
You can check out complete tutorial given below.
Managing-Your-JavaScript-Library-in-ASP-NET
You can do it by using master page. Demo like
<master page>
<header>
//add script file here
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js"></script>
//Other scripts
</header>
<content>
<Sub pages>
//Here you can debase your pages(like dynamically change pages), So the header script will referred from above header
</content>
<footer>
<//footer>
<master page>
MSDN link for Master page
If you don't want to use a master page you could use a server control and add it to the pages as needed.
Adding a Master Page is good.
As an alternate way, you can achieve this by creating a base page and adding scripts from web.config file into the page's header by overriding Page class OnInit event.
Create a class as BasePage inheriting from System.Web.UI.Page like
public class BasePage : System.Web.UI.Page
{
}
On all the pages where you want to load the scripts, inherit them from BasePage
Earlier
public partial class _Default : System.Web.UI.Page
{
}
Now
public partial class _Default : BasePage
{
}
Mention your script files at One place - Web.Config as below
<appSettings>
<add key="ScriptJquery" value="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"/>
<add key="ScriptJqueryUI" value="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"/>
</appSettings>
In the BasePage Class override OnInit as below
public class BasePage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
IEnumerable<string> scripts = ConfigurationManager.AppSettings.Keys.OfType<string>().Where(s => s.StartsWith("Script"));
foreach (string script in scripts)
{
Literal scriptTag = new Literal();
scriptTag.Text = string.Format(#"<script src=""{0}"" type=""text/javascript""></script>",ConfigurationManager.AppSettings[script].ToString());
Page.Header.Controls.Add(scriptTag);
}
base.OnInit(e);
}
}
I have a site where 6 css files are linked, But in a page i need to use only 3 css files. My developers are using master page in .net, so they don't want to change that. So, my question is: Is there any way I can skip few css files which is linked?
It is not very 'elegant' but you can use a jQuery script to manipulate and remove the link:
<script type="text/javascript">
$(document).ready(function () {
$("link[type='text/css']").remove();
});
</script>
You can use jQuery selector to refine the search. I.e.
$("link[href='Styles/Site.css']").remove();
Another solution (doesn't need jQuery) is adding a configuration property to the master page like this:
Site.Master.cs
private bool _IncludeOtherCss = true;
public bool IncludeOtherCss {
get { return _IncludeOtherCss; }
set { _IncludeOtherCss = value; }
}
Site.Master (head section)
<%if (IncludeOtherCss)
{ %>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<%} %>
Other page:
protected void Page_Init(object sender, EventArgs e)
{
(Master as SiteMaster).IncludeOtherCss = false;
}
So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png
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>