JS 파일에 jQuery를 추가하는 방법
테이블 정렬과 관련된 코드가 있습니다. 코드는 대부분의 페이지에서 일반적이므로 코드가있는 JS 파일을 만들고 싶습니다.이 코드를 사용하는 모든 페이지는 거기에서 참조 할 수 있습니다.
문제는 : jQuery 및 테이블 정렬 플러그인을 해당 .js 파일에 어떻게 추가합니까?
나는 이와 같은 것을 시도했다 :
document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');
그러나 이것은 작동하지 않는 것 같습니다.
가장 좋은 방법은 무엇입니까?
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
다른 JS 파일의 jQuery 코드를 포함하려면 다음과 같은 트릭을 수행해야합니다.
내 HTML 파일에 다음이 있습니다.
<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>
다음을 사용하여 별도의 my_jquery.js 파일을 만들었습니다.
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
$(this).hide("slow");
});
});
아래 코드를 사용하여 JS 파일에서 jQuery를로드 할 수 있습니다. 또한 작동하고 자체 호출 기능을 사용하는 jQuery JSFiddle을 추가했습니다.
// 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!");
});
});
})();
기타 옵션 : -JS 모듈 로더 인 Require.JS 를 사용해 볼 수도 있습니다 .
프로젝트에서 js 파일에 대한 참조를 추가하려는 경우 참조 태그를 사용하여 직접 추가 할 수도 있습니다 .Visual Studio IDE에서는 외부 파일을 솔루션 탐색기에서 현재 파일로 끌어서 놓아 자동으로 처리됩니다 ( 마크 업 파일, .js 및 .css 파일에서도 작동합니다.)
/// <reference path="jquery-2.0.3.js" />
/* 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 :)');
}
문제는 </script>
스크립트 내에서 스크립트 태그를 끝내는 중입니다. 이 시도:
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>');
다음은 다른 포럼에서 제안 된 솔루션의 조합으로 채택한 솔루션입니다.
이 방법으로 하나의 js 파일에서 css 파일과 다른 js 파일을 모두 참조 할 수 있으므로 한 번에 한 번만 변경하면됩니다. 궁금한 점이 있으면 알려주세요.
나는 다음을 수행했다.
- jQueryIncluder.js라는 이름으로 js를 만들었습니다.
이 파일에서 다음 코드를 선언하고 실행했습니다.
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();
내 .Net 프로젝트의 다른 js 또는 xsl 파일에서 위의 jQueryIncluder.js 파일을 다음과 같이 참조했습니다.
<script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
내 노력에 감사드립니다.
감사
다른 js 파일로 js 파일을 가져올 수 없습니다
js에서 jquery를 사용하는 방법은
html 또는 js 파일을 포함 할 내부의 사용중인 모든보기 페이지에서 js 가져 오기
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');
});
});
이것은 확실히 당신을 위해 작동합니다
필요한 다른 파일을 다른 js 파일에 포함시킬 수있는 jquery 플러그인이 있습니다. http://tobiasz123.wordpress.com/2007/08/01/include-script-inclusion-jquery- 플러그인 / .
또한이 document.write 줄은 js 파일이 아닌 html로 스크립트 태그를 작성합니다.
그래서 이것이 당신의 문제에 조금 도움이되기를 바랍니다.
jquery 파일 링크를 여러 페이지의 여러 사이트에서 한 번에 새 버전 파일로 자주 업데이트하려는 경우 ..
자바 스크립트 파일 (.js)을 만들고 아래 코드를 넣고이 페이지에서 직접 jquery 파일을 매핑하는 대신이 페이지를 javascript 파일로 매핑하십시오. 따라서 jquery 파일 링크 가이 javascript 파일에서 업데이트되면 사이트 전체에 반영하십시오.
아래 코드는 테스트되었으며 잘 작동합니다!
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('>');
포함 된 js 및 jquery 파일없이 마스터 페이지 기반을 만들 수 있습니다. 헤드 섹션의 마스터 페이지베이스에 컨텐츠 플레이스 홀더를 놓은 후이 마스터 페이지베이스에서 상속되는 중첩 된 마스터 페이지를 작성하십시오. 이제 중첩 마스터 페이지의 asp : content에 포함을 넣고 마지막으로이 중첩 마스터 페이지에서 컨텐츠 페이지를 작성하십시오.
예:
//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 script for JQuery but issue is it takes time to load while next statement in javascript using $ fails. So I used below solution.
myscript.js is having code which use JQuery main.js is used to load both jquery js file and myscript.js file 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 going to next statement which use $.
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>
참고URL : https://stackoverflow.com/questions/1140402/how-to-add-jquery-in-js-file
'Programing' 카테고리의 다른 글
PHP는 속성이 객체 또는 클래스에 존재하는지 확인 (0) | 2020.07.07 |
---|---|
linq에서 2 개의 필드로 orderby를 사용하는 방법은 무엇입니까? (0) | 2020.07.07 |
play2의 모든 곳에서 매개 변수를 전달하지 않는 방법은 무엇입니까? (0) | 2020.07.07 |
지원되지 않는 Xcode iOS 8 키보드 유형 (0) | 2020.07.07 |
일반 목록을 CSV 문자열로 변환 (0) | 2020.07.07 |